Home | History | Annotate | Line # | Download | only in python
py-inferior.c revision 1.6
      1 /* Python interface to inferiors.
      2 
      3    Copyright (C) 2009-2016 Free Software Foundation, Inc.
      4 
      5    This file is part of GDB.
      6 
      7    This program is free software; you can redistribute it and/or modify
      8    it under the terms of the GNU General Public License as published by
      9    the Free Software Foundation; either version 3 of the License, or
     10    (at your option) any later version.
     11 
     12    This program is distributed in the hope that it will be useful,
     13    but WITHOUT ANY WARRANTY; without even the implied warranty of
     14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     15    GNU General Public License for more details.
     16 
     17    You should have received a copy of the GNU General Public License
     18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
     19 
     20 #include "defs.h"
     21 #include "gdbcore.h"
     22 #include "gdbthread.h"
     23 #include "inferior.h"
     24 #include "objfiles.h"
     25 #include "observer.h"
     26 #include "python-internal.h"
     27 #include "arch-utils.h"
     28 #include "language.h"
     29 #include "gdb_signals.h"
     30 #include "py-event.h"
     31 #include "py-stopevent.h"
     32 
     33 struct threadlist_entry {
     34   thread_object *thread_obj;
     35   struct threadlist_entry *next;
     36 };
     37 
     38 typedef struct
     39 {
     40   PyObject_HEAD
     41 
     42   /* The inferior we represent.  */
     43   struct inferior *inferior;
     44 
     45   /* thread_object instances under this inferior.  This list owns a
     46      reference to each object it contains.  */
     47   struct threadlist_entry *threads;
     48 
     49   /* Number of threads in the list.  */
     50   int nthreads;
     51 } inferior_object;
     52 
     53 extern PyTypeObject inferior_object_type
     54     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("inferior_object");
     55 
     56 static const struct inferior_data *infpy_inf_data_key;
     57 
     58 typedef struct {
     59   PyObject_HEAD
     60   void *buffer;
     61 
     62   /* These are kept just for mbpy_str.  */
     63   CORE_ADDR addr;
     64   CORE_ADDR length;
     65 } membuf_object;
     66 
     67 extern PyTypeObject membuf_object_type
     68     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("membuf_object");
     69 
     70 /* Require that INFERIOR be a valid inferior ID.  */
     71 #define INFPY_REQUIRE_VALID(Inferior)				\
     72   do {								\
     73     if (!Inferior->inferior)					\
     74       {								\
     75 	PyErr_SetString (PyExc_RuntimeError,			\
     76 			 _("Inferior no longer exists."));	\
     77 	return NULL;						\
     78       }								\
     79   } while (0)
     80 
     81 static void
     82 python_on_normal_stop (struct bpstats *bs, int print_frame)
     83 {
     84   struct cleanup *cleanup;
     85   enum gdb_signal stop_signal;
     86 
     87   if (!gdb_python_initialized)
     88     return;
     89 
     90   if (!find_thread_ptid (inferior_ptid))
     91       return;
     92 
     93   stop_signal = inferior_thread ()->suspend.stop_signal;
     94 
     95   cleanup = ensure_python_env (get_current_arch (), current_language);
     96 
     97   if (emit_stop_event (bs, stop_signal) < 0)
     98     gdbpy_print_stack ();
     99 
    100   do_cleanups (cleanup);
    101 }
    102 
    103 static void
    104 python_on_resume (ptid_t ptid)
    105 {
    106   struct cleanup *cleanup;
    107 
    108   if (!gdb_python_initialized)
    109     return;
    110 
    111   cleanup = ensure_python_env (target_gdbarch (), current_language);
    112 
    113   if (emit_continue_event (ptid) < 0)
    114     gdbpy_print_stack ();
    115 
    116   do_cleanups (cleanup);
    117 }
    118 
    119 /* Callback, registered as an observer, that notifies Python listeners
    120    when an inferior function call is about to be made. */
    121 
    122 static void
    123 python_on_inferior_call_pre (ptid_t thread, CORE_ADDR address)
    124 {
    125   struct cleanup *cleanup;
    126 
    127   cleanup = ensure_python_env (target_gdbarch (), current_language);
    128 
    129   if (emit_inferior_call_event (INFERIOR_CALL_PRE, thread, address) < 0)
    130     gdbpy_print_stack ();
    131 
    132   do_cleanups (cleanup);
    133 }
    134 
    135 /* Callback, registered as an observer, that notifies Python listeners
    136    when an inferior function call has completed. */
    137 
    138 static void
    139 python_on_inferior_call_post (ptid_t thread, CORE_ADDR address)
    140 {
    141   struct cleanup *cleanup;
    142 
    143   cleanup = ensure_python_env (target_gdbarch (), current_language);
    144 
    145   if (emit_inferior_call_event (INFERIOR_CALL_POST, thread, address) < 0)
    146     gdbpy_print_stack ();
    147 
    148   do_cleanups (cleanup);
    149 }
    150 
    151 /* Callback, registered as an observer, that notifies Python listeners
    152    when a part of memory has been modified by user action (eg via a
    153    'set' command). */
    154 
    155 static void
    156 python_on_memory_change (struct inferior *inferior, CORE_ADDR addr, ssize_t len, const bfd_byte *data)
    157 {
    158   struct cleanup *cleanup;
    159 
    160   cleanup = ensure_python_env (target_gdbarch (), current_language);
    161 
    162   if (emit_memory_changed_event (addr, len) < 0)
    163     gdbpy_print_stack ();
    164 
    165   do_cleanups (cleanup);
    166 }
    167 
    168 /* Callback, registered as an observer, that notifies Python listeners
    169    when a register has been modified by user action (eg via a 'set'
    170    command). */
    171 
    172 static void
    173 python_on_register_change (struct frame_info *frame, int regnum)
    174 {
    175   struct cleanup *cleanup;
    176 
    177   cleanup = ensure_python_env (target_gdbarch (), current_language);
    178 
    179   if (emit_register_changed_event (frame, regnum) < 0)
    180     gdbpy_print_stack ();
    181 
    182   do_cleanups (cleanup);
    183 }
    184 
    185 static void
    186 python_inferior_exit (struct inferior *inf)
    187 {
    188   struct cleanup *cleanup;
    189   const LONGEST *exit_code = NULL;
    190 
    191   if (!gdb_python_initialized)
    192     return;
    193 
    194   cleanup = ensure_python_env (target_gdbarch (), current_language);
    195 
    196   if (inf->has_exit_code)
    197     exit_code = &inf->exit_code;
    198 
    199   if (emit_exited_event (exit_code, inf) < 0)
    200     gdbpy_print_stack ();
    201 
    202   do_cleanups (cleanup);
    203 }
    204 
    205 /* Callback used to notify Python listeners about new objfiles loaded in the
    206    inferior.  OBJFILE may be NULL which means that the objfile list has been
    207    cleared (emptied).  */
    208 
    209 static void
    210 python_new_objfile (struct objfile *objfile)
    211 {
    212   struct cleanup *cleanup;
    213 
    214   if (!gdb_python_initialized)
    215     return;
    216 
    217   cleanup = ensure_python_env (objfile != NULL
    218 			       ? get_objfile_arch (objfile)
    219 			       : target_gdbarch (),
    220 			       current_language);
    221 
    222   if (objfile == NULL)
    223     {
    224       if (emit_clear_objfiles_event () < 0)
    225 	gdbpy_print_stack ();
    226     }
    227   else
    228     {
    229       if (emit_new_objfile_event (objfile) < 0)
    230 	gdbpy_print_stack ();
    231     }
    232 
    233   do_cleanups (cleanup);
    234 }
    235 
    236 /* Return a reference to the Python object of type Inferior
    237    representing INFERIOR.  If the object has already been created,
    238    return it and increment the reference count,  otherwise, create it.
    239    Return NULL on failure.  */
    240 PyObject *
    241 inferior_to_inferior_object (struct inferior *inferior)
    242 {
    243   inferior_object *inf_obj;
    244 
    245   inf_obj = (inferior_object *) inferior_data (inferior, infpy_inf_data_key);
    246   if (!inf_obj)
    247     {
    248       inf_obj = PyObject_New (inferior_object, &inferior_object_type);
    249       if (!inf_obj)
    250 	  return NULL;
    251 
    252       inf_obj->inferior = inferior;
    253       inf_obj->threads = NULL;
    254       inf_obj->nthreads = 0;
    255 
    256       set_inferior_data (inferior, infpy_inf_data_key, inf_obj);
    257 
    258     }
    259   else
    260     Py_INCREF ((PyObject *)inf_obj);
    261 
    262   return (PyObject *) inf_obj;
    263 }
    264 
    265 /* Finds the Python Inferior object for the given PID.  Returns a
    266    reference, or NULL if PID does not match any inferior object. */
    267 
    268 PyObject *
    269 find_inferior_object (int pid)
    270 {
    271   struct inferior *inf = find_inferior_pid (pid);
    272 
    273   if (inf)
    274     return inferior_to_inferior_object (inf);
    275 
    276   return NULL;
    277 }
    278 
    279 thread_object *
    280 find_thread_object (ptid_t ptid)
    281 {
    282   int pid;
    283   struct threadlist_entry *thread;
    284   PyObject *inf_obj;
    285   thread_object *found = NULL;
    286 
    287   pid = ptid_get_pid (ptid);
    288   if (pid == 0)
    289     return NULL;
    290 
    291   inf_obj = find_inferior_object (pid);
    292 
    293   if (! inf_obj)
    294     return NULL;
    295 
    296   for (thread = ((inferior_object *)inf_obj)->threads; thread;
    297        thread = thread->next)
    298     if (ptid_equal (thread->thread_obj->thread->ptid, ptid))
    299       {
    300 	found = thread->thread_obj;
    301 	break;
    302       }
    303 
    304   Py_DECREF (inf_obj);
    305 
    306   if (found)
    307     return found;
    308 
    309   return NULL;
    310 }
    311 
    312 static void
    313 add_thread_object (struct thread_info *tp)
    314 {
    315   struct cleanup *cleanup;
    316   thread_object *thread_obj;
    317   inferior_object *inf_obj;
    318   struct threadlist_entry *entry;
    319 
    320   if (!gdb_python_initialized)
    321     return;
    322 
    323   cleanup = ensure_python_env (python_gdbarch, python_language);
    324 
    325   thread_obj = create_thread_object (tp);
    326   if (!thread_obj)
    327     {
    328       gdbpy_print_stack ();
    329       do_cleanups (cleanup);
    330       return;
    331     }
    332 
    333   inf_obj = (inferior_object *) thread_obj->inf_obj;
    334 
    335   entry = XNEW (struct threadlist_entry);
    336   entry->thread_obj = thread_obj;
    337   entry->next = inf_obj->threads;
    338 
    339   inf_obj->threads = entry;
    340   inf_obj->nthreads++;
    341 
    342   do_cleanups (cleanup);
    343 }
    344 
    345 static void
    346 delete_thread_object (struct thread_info *tp, int ignore)
    347 {
    348   struct cleanup *cleanup;
    349   inferior_object *inf_obj;
    350   struct threadlist_entry **entry, *tmp;
    351 
    352   if (!gdb_python_initialized)
    353     return;
    354 
    355   cleanup = ensure_python_env (python_gdbarch, python_language);
    356 
    357   inf_obj
    358     = (inferior_object *) find_inferior_object (ptid_get_pid (tp->ptid));
    359   if (!inf_obj)
    360     {
    361       do_cleanups (cleanup);
    362       return;
    363     }
    364 
    365   /* Find thread entry in its inferior's thread_list.  */
    366   for (entry = &inf_obj->threads; *entry != NULL; entry =
    367 	 &(*entry)->next)
    368     if ((*entry)->thread_obj->thread == tp)
    369       break;
    370 
    371   if (!*entry)
    372     {
    373       Py_DECREF (inf_obj);
    374       do_cleanups (cleanup);
    375       return;
    376     }
    377 
    378   tmp = *entry;
    379   tmp->thread_obj->thread = NULL;
    380 
    381   *entry = (*entry)->next;
    382   inf_obj->nthreads--;
    383 
    384   Py_DECREF (tmp->thread_obj);
    385   Py_DECREF (inf_obj);
    386   xfree (tmp);
    387 
    388   do_cleanups (cleanup);
    389 }
    390 
    391 static PyObject *
    392 infpy_threads (PyObject *self, PyObject *args)
    393 {
    394   int i;
    395   struct threadlist_entry *entry;
    396   inferior_object *inf_obj = (inferior_object *) self;
    397   PyObject *tuple;
    398 
    399   INFPY_REQUIRE_VALID (inf_obj);
    400 
    401   TRY
    402     {
    403       update_thread_list ();
    404     }
    405   CATCH (except, RETURN_MASK_ALL)
    406     {
    407       GDB_PY_HANDLE_EXCEPTION (except);
    408     }
    409   END_CATCH
    410 
    411   tuple = PyTuple_New (inf_obj->nthreads);
    412   if (!tuple)
    413     return NULL;
    414 
    415   for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
    416        i++, entry = entry->next)
    417     {
    418       Py_INCREF (entry->thread_obj);
    419       PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
    420     }
    421 
    422   return tuple;
    423 }
    424 
    425 static PyObject *
    426 infpy_get_num (PyObject *self, void *closure)
    427 {
    428   inferior_object *inf = (inferior_object *) self;
    429 
    430   INFPY_REQUIRE_VALID (inf);
    431 
    432   return PyLong_FromLong (inf->inferior->num);
    433 }
    434 
    435 static PyObject *
    436 infpy_get_pid (PyObject *self, void *closure)
    437 {
    438   inferior_object *inf = (inferior_object *) self;
    439 
    440   INFPY_REQUIRE_VALID (inf);
    441 
    442   return PyLong_FromLong (inf->inferior->pid);
    443 }
    444 
    445 static PyObject *
    446 infpy_get_was_attached (PyObject *self, void *closure)
    447 {
    448   inferior_object *inf = (inferior_object *) self;
    449 
    450   INFPY_REQUIRE_VALID (inf);
    451   if (inf->inferior->attach_flag)
    452     Py_RETURN_TRUE;
    453   Py_RETURN_FALSE;
    454 }
    455 
    456 static int
    457 build_inferior_list (struct inferior *inf, void *arg)
    458 {
    459   PyObject *list = (PyObject *) arg;
    460   PyObject *inferior = inferior_to_inferior_object (inf);
    461   int success = 0;
    462 
    463   if (! inferior)
    464     return 0;
    465 
    466   success = PyList_Append (list, inferior);
    467   Py_DECREF (inferior);
    468 
    469   if (success)
    470     return 1;
    471 
    472   return 0;
    473 }
    474 
    475 /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
    476    Returns a tuple of all inferiors.  */
    477 PyObject *
    478 gdbpy_inferiors (PyObject *unused, PyObject *unused2)
    479 {
    480   PyObject *list, *tuple;
    481 
    482   list = PyList_New (0);
    483   if (!list)
    484     return NULL;
    485 
    486   if (iterate_over_inferiors (build_inferior_list, list))
    487     {
    488       Py_DECREF (list);
    489       return NULL;
    490     }
    491 
    492   tuple = PyList_AsTuple (list);
    493   Py_DECREF (list);
    494 
    495   return tuple;
    496 }
    497 
    498 /* Membuf and memory manipulation.  */
    499 
    500 /* Implementation of Inferior.read_memory (address, length).
    501    Returns a Python buffer object with LENGTH bytes of the inferior's
    502    memory at ADDRESS.  Both arguments are integers.  Returns NULL on error,
    503    with a python exception set.  */
    504 static PyObject *
    505 infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
    506 {
    507   CORE_ADDR addr, length;
    508   gdb_byte *buffer = NULL;
    509   membuf_object *membuf_obj;
    510   PyObject *addr_obj, *length_obj, *result;
    511   static char *keywords[] = { "address", "length", NULL };
    512 
    513   if (! PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
    514 				     &addr_obj, &length_obj))
    515     return NULL;
    516 
    517   if (get_addr_from_python (addr_obj, &addr) < 0
    518       || get_addr_from_python (length_obj, &length) < 0)
    519     return NULL;
    520 
    521   TRY
    522     {
    523       buffer = (gdb_byte *) xmalloc (length);
    524 
    525       read_memory (addr, buffer, length);
    526     }
    527   CATCH (except, RETURN_MASK_ALL)
    528     {
    529       xfree (buffer);
    530       GDB_PY_HANDLE_EXCEPTION (except);
    531     }
    532   END_CATCH
    533 
    534   membuf_obj = PyObject_New (membuf_object, &membuf_object_type);
    535   if (membuf_obj == NULL)
    536     {
    537       xfree (buffer);
    538       return NULL;
    539     }
    540 
    541   membuf_obj->buffer = buffer;
    542   membuf_obj->addr = addr;
    543   membuf_obj->length = length;
    544 
    545 #ifdef IS_PY3K
    546   result = PyMemoryView_FromObject ((PyObject *) membuf_obj);
    547 #else
    548   result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
    549 					 Py_END_OF_BUFFER);
    550 #endif
    551   Py_DECREF (membuf_obj);
    552 
    553   return result;
    554 }
    555 
    556 /* Implementation of Inferior.write_memory (address, buffer [, length]).
    557    Writes the contents of BUFFER (a Python object supporting the read
    558    buffer protocol) at ADDRESS in the inferior's memory.  Write LENGTH
    559    bytes from BUFFER, or its entire contents if the argument is not
    560    provided.  The function returns nothing.  Returns NULL on error, with
    561    a python exception set.  */
    562 static PyObject *
    563 infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
    564 {
    565   struct gdb_exception except = exception_none;
    566   Py_ssize_t buf_len;
    567   const gdb_byte *buffer;
    568   CORE_ADDR addr, length;
    569   PyObject *addr_obj, *length_obj = NULL;
    570   static char *keywords[] = { "address", "buffer", "length", NULL };
    571 #ifdef IS_PY3K
    572   Py_buffer pybuf;
    573 
    574   if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
    575 				     &addr_obj, &pybuf,
    576 				     &length_obj))
    577     return NULL;
    578 
    579   buffer = (const gdb_byte *) pybuf.buf;
    580   buf_len = pybuf.len;
    581 #else
    582   if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
    583 				     &addr_obj, &buffer, &buf_len,
    584 				     &length_obj))
    585     return NULL;
    586 
    587   buffer = (const gdb_byte *) buffer;
    588 #endif
    589 
    590   if (get_addr_from_python (addr_obj, &addr) < 0)
    591     goto fail;
    592 
    593   if (!length_obj)
    594     length = buf_len;
    595   else if (get_addr_from_python (length_obj, &length) < 0)
    596     goto fail;
    597 
    598   TRY
    599     {
    600       write_memory_with_notification (addr, buffer, length);
    601     }
    602   CATCH (ex, RETURN_MASK_ALL)
    603     {
    604       except = ex;
    605     }
    606   END_CATCH
    607 
    608 #ifdef IS_PY3K
    609   PyBuffer_Release (&pybuf);
    610 #endif
    611   GDB_PY_HANDLE_EXCEPTION (except);
    612 
    613   Py_RETURN_NONE;
    614 
    615  fail:
    616 #ifdef IS_PY3K
    617   PyBuffer_Release (&pybuf);
    618 #endif
    619   return NULL;
    620 }
    621 
    622 /* Destructor of Membuf objects.  */
    623 static void
    624 mbpy_dealloc (PyObject *self)
    625 {
    626   xfree (((membuf_object *) self)->buffer);
    627   Py_TYPE (self)->tp_free (self);
    628 }
    629 
    630 /* Return a description of the Membuf object.  */
    631 static PyObject *
    632 mbpy_str (PyObject *self)
    633 {
    634   membuf_object *membuf_obj = (membuf_object *) self;
    635 
    636   return PyString_FromFormat (_("Memory buffer for address %s, \
    637 which is %s bytes long."),
    638 			      paddress (python_gdbarch, membuf_obj->addr),
    639 			      pulongest (membuf_obj->length));
    640 }
    641 
    642 #ifdef IS_PY3K
    643 
    644 static int
    645 get_buffer (PyObject *self, Py_buffer *buf, int flags)
    646 {
    647   membuf_object *membuf_obj = (membuf_object *) self;
    648   int ret;
    649 
    650   ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer,
    651 			   membuf_obj->length, 0,
    652 			   PyBUF_CONTIG);
    653   buf->format = "c";
    654 
    655   return ret;
    656 }
    657 
    658 #else
    659 
    660 static Py_ssize_t
    661 get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
    662 {
    663   membuf_object *membuf_obj = (membuf_object *) self;
    664 
    665   if (segment)
    666     {
    667       PyErr_SetString (PyExc_SystemError,
    668 		       _("The memory buffer supports only one segment."));
    669       return -1;
    670     }
    671 
    672   *ptrptr = membuf_obj->buffer;
    673 
    674   return membuf_obj->length;
    675 }
    676 
    677 static Py_ssize_t
    678 get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
    679 {
    680   return get_read_buffer (self, segment, ptrptr);
    681 }
    682 
    683 static Py_ssize_t
    684 get_seg_count (PyObject *self, Py_ssize_t *lenp)
    685 {
    686   if (lenp)
    687     *lenp = ((membuf_object *) self)->length;
    688 
    689   return 1;
    690 }
    691 
    692 static Py_ssize_t
    693 get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
    694 {
    695   void *ptr = NULL;
    696   Py_ssize_t ret;
    697 
    698   ret = get_read_buffer (self, segment, &ptr);
    699   *ptrptr = (char *) ptr;
    700 
    701   return ret;
    702 }
    703 
    704 #endif	/* IS_PY3K */
    705 
    706 /* Implementation of
    707    gdb.search_memory (address, length, pattern).  ADDRESS is the
    708    address to start the search.  LENGTH specifies the scope of the
    709    search from ADDRESS.  PATTERN is the pattern to search for (and
    710    must be a Python object supporting the buffer protocol).
    711    Returns a Python Long object holding the address where the pattern
    712    was located, or if the pattern was not found, returns None.  Returns NULL
    713    on error, with a python exception set.  */
    714 static PyObject *
    715 infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
    716 {
    717   struct gdb_exception except = exception_none;
    718   CORE_ADDR start_addr, length;
    719   static char *keywords[] = { "address", "length", "pattern", NULL };
    720   PyObject *start_addr_obj, *length_obj;
    721   Py_ssize_t pattern_size;
    722   const gdb_byte *buffer;
    723   CORE_ADDR found_addr;
    724   int found = 0;
    725 #ifdef IS_PY3K
    726   Py_buffer pybuf;
    727 
    728   if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
    729 				     &start_addr_obj, &length_obj,
    730 				     &pybuf))
    731     return NULL;
    732 
    733   buffer = (const gdb_byte *) pybuf.buf;
    734   pattern_size = pybuf.len;
    735 #else
    736   PyObject *pattern;
    737   const void *vbuffer;
    738 
    739   if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
    740  				     &start_addr_obj, &length_obj,
    741 				     &pattern))
    742      return NULL;
    743 
    744   if (!PyObject_CheckReadBuffer (pattern))
    745     {
    746       PyErr_SetString (PyExc_RuntimeError,
    747 		       _("The pattern is not a Python buffer."));
    748 
    749       return NULL;
    750     }
    751 
    752   if (PyObject_AsReadBuffer (pattern, &vbuffer, &pattern_size) == -1)
    753     return NULL;
    754 
    755   buffer = (const gdb_byte *) vbuffer;
    756 #endif
    757 
    758   if (get_addr_from_python (start_addr_obj, &start_addr) < 0)
    759     goto fail;
    760 
    761   if (get_addr_from_python (length_obj, &length) < 0)
    762     goto fail;
    763 
    764   if (!length)
    765     {
    766       PyErr_SetString (PyExc_ValueError,
    767 		       _("Search range is empty."));
    768       goto fail;
    769     }
    770   /* Watch for overflows.  */
    771   else if (length > CORE_ADDR_MAX
    772 	   || (start_addr + length - 1) < start_addr)
    773     {
    774       PyErr_SetString (PyExc_ValueError,
    775 		       _("The search range is too large."));
    776       goto fail;
    777     }
    778 
    779   TRY
    780     {
    781       found = target_search_memory (start_addr, length,
    782 				    buffer, pattern_size,
    783 				    &found_addr);
    784     }
    785   CATCH (ex, RETURN_MASK_ALL)
    786     {
    787       except = ex;
    788     }
    789   END_CATCH
    790 
    791 #ifdef IS_PY3K
    792   PyBuffer_Release (&pybuf);
    793 #endif
    794   GDB_PY_HANDLE_EXCEPTION (except);
    795 
    796   if (found)
    797     return PyLong_FromLong (found_addr);
    798   else
    799     Py_RETURN_NONE;
    800 
    801  fail:
    802 #ifdef IS_PY3K
    803   PyBuffer_Release (&pybuf);
    804 #endif
    805   return NULL;
    806 }
    807 
    808 /* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
    809    Returns True if this inferior object still exists in GDB.  */
    810 
    811 static PyObject *
    812 infpy_is_valid (PyObject *self, PyObject *args)
    813 {
    814   inferior_object *inf = (inferior_object *) self;
    815 
    816   if (! inf->inferior)
    817     Py_RETURN_FALSE;
    818 
    819   Py_RETURN_TRUE;
    820 }
    821 
    822 static void
    823 infpy_dealloc (PyObject *obj)
    824 {
    825   inferior_object *inf_obj = (inferior_object *) obj;
    826   struct inferior *inf = inf_obj->inferior;
    827 
    828   if (! inf)
    829     return;
    830 
    831   set_inferior_data (inf, infpy_inf_data_key, NULL);
    832 }
    833 
    834 /* Clear the INFERIOR pointer in an Inferior object and clear the
    835    thread list.  */
    836 static void
    837 py_free_inferior (struct inferior *inf, void *datum)
    838 {
    839 
    840   struct cleanup *cleanup;
    841   inferior_object *inf_obj = (inferior_object *) datum;
    842   struct threadlist_entry *th_entry, *th_tmp;
    843 
    844   if (!gdb_python_initialized)
    845     return;
    846 
    847   cleanup = ensure_python_env (python_gdbarch, python_language);
    848 
    849   inf_obj->inferior = NULL;
    850 
    851   /* Deallocate threads list.  */
    852   for (th_entry = inf_obj->threads; th_entry != NULL;)
    853     {
    854       Py_DECREF (th_entry->thread_obj);
    855 
    856       th_tmp = th_entry;
    857       th_entry = th_entry->next;
    858       xfree (th_tmp);
    859     }
    860 
    861   inf_obj->nthreads = 0;
    862 
    863   Py_DECREF ((PyObject *) inf_obj);
    864   do_cleanups (cleanup);
    865 }
    866 
    867 /* Implementation of gdb.selected_inferior() -> gdb.Inferior.
    868    Returns the current inferior object.  */
    869 
    870 PyObject *
    871 gdbpy_selected_inferior (PyObject *self, PyObject *args)
    872 {
    873   return inferior_to_inferior_object (current_inferior ());
    874 }
    875 
    876 int
    877 gdbpy_initialize_inferior (void)
    878 {
    879   if (PyType_Ready (&inferior_object_type) < 0)
    880     return -1;
    881 
    882   if (gdb_pymodule_addobject (gdb_module, "Inferior",
    883 			      (PyObject *) &inferior_object_type) < 0)
    884     return -1;
    885 
    886   infpy_inf_data_key =
    887     register_inferior_data_with_cleanup (NULL, py_free_inferior);
    888 
    889   observer_attach_new_thread (add_thread_object);
    890   observer_attach_thread_exit (delete_thread_object);
    891   observer_attach_normal_stop (python_on_normal_stop);
    892   observer_attach_target_resumed (python_on_resume);
    893   observer_attach_inferior_call_pre (python_on_inferior_call_pre);
    894   observer_attach_inferior_call_post (python_on_inferior_call_post);
    895   observer_attach_memory_changed (python_on_memory_change);
    896   observer_attach_register_changed (python_on_register_change);
    897   observer_attach_inferior_exit (python_inferior_exit);
    898   observer_attach_new_objfile (python_new_objfile);
    899 
    900   membuf_object_type.tp_new = PyType_GenericNew;
    901   if (PyType_Ready (&membuf_object_type) < 0)
    902     return -1;
    903 
    904   return gdb_pymodule_addobject (gdb_module, "Membuf", (PyObject *)
    905 				 &membuf_object_type);
    906 }
    907 
    908 static PyGetSetDef inferior_object_getset[] =
    909 {
    910   { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
    911   { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
    912     NULL },
    913   { "was_attached", infpy_get_was_attached, NULL,
    914     "True if the inferior was created using 'attach'.", NULL },
    915   { NULL }
    916 };
    917 
    918 static PyMethodDef inferior_object_methods[] =
    919 {
    920   { "is_valid", infpy_is_valid, METH_NOARGS,
    921     "is_valid () -> Boolean.\n\
    922 Return true if this inferior is valid, false if not." },
    923   { "threads", infpy_threads, METH_NOARGS,
    924     "Return all the threads of this inferior." },
    925   { "read_memory", (PyCFunction) infpy_read_memory,
    926     METH_VARARGS | METH_KEYWORDS,
    927     "read_memory (address, length) -> buffer\n\
    928 Return a buffer object for reading from the inferior's memory." },
    929   { "write_memory", (PyCFunction) infpy_write_memory,
    930     METH_VARARGS | METH_KEYWORDS,
    931     "write_memory (address, buffer [, length])\n\
    932 Write the given buffer object to the inferior's memory." },
    933   { "search_memory", (PyCFunction) infpy_search_memory,
    934     METH_VARARGS | METH_KEYWORDS,
    935     "search_memory (address, length, pattern) -> long\n\
    936 Return a long with the address of a match, or None." },
    937   { NULL }
    938 };
    939 
    940 PyTypeObject inferior_object_type =
    941 {
    942   PyVarObject_HEAD_INIT (NULL, 0)
    943   "gdb.Inferior",		  /* tp_name */
    944   sizeof (inferior_object),	  /* tp_basicsize */
    945   0,				  /* tp_itemsize */
    946   infpy_dealloc,		  /* tp_dealloc */
    947   0,				  /* tp_print */
    948   0,				  /* tp_getattr */
    949   0,				  /* tp_setattr */
    950   0,				  /* tp_compare */
    951   0,				  /* tp_repr */
    952   0,				  /* tp_as_number */
    953   0,				  /* tp_as_sequence */
    954   0,				  /* tp_as_mapping */
    955   0,				  /* tp_hash  */
    956   0,				  /* tp_call */
    957   0,				  /* tp_str */
    958   0,				  /* tp_getattro */
    959   0,				  /* tp_setattro */
    960   0,				  /* tp_as_buffer */
    961   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER,  /* tp_flags */
    962   "GDB inferior object",	  /* tp_doc */
    963   0,				  /* tp_traverse */
    964   0,				  /* tp_clear */
    965   0,				  /* tp_richcompare */
    966   0,				  /* tp_weaklistoffset */
    967   0,				  /* tp_iter */
    968   0,				  /* tp_iternext */
    969   inferior_object_methods,	  /* tp_methods */
    970   0,				  /* tp_members */
    971   inferior_object_getset,	  /* tp_getset */
    972   0,				  /* tp_base */
    973   0,				  /* tp_dict */
    974   0,				  /* tp_descr_get */
    975   0,				  /* tp_descr_set */
    976   0,				  /* tp_dictoffset */
    977   0,				  /* tp_init */
    978   0				  /* tp_alloc */
    979 };
    980 
    981 #ifdef IS_PY3K
    982 
    983 static PyBufferProcs buffer_procs =
    984 {
    985   get_buffer
    986 };
    987 
    988 #else
    989 
    990 /* Python doesn't provide a decent way to get compatibility here.  */
    991 #if HAVE_LIBPYTHON2_4
    992 #define CHARBUFFERPROC_NAME getcharbufferproc
    993 #else
    994 #define CHARBUFFERPROC_NAME charbufferproc
    995 #endif
    996 
    997 static PyBufferProcs buffer_procs = {
    998   get_read_buffer,
    999   get_write_buffer,
   1000   get_seg_count,
   1001   /* The cast here works around a difference between Python 2.4 and
   1002      Python 2.5.  */
   1003   (CHARBUFFERPROC_NAME) get_char_buffer
   1004 };
   1005 #endif	/* IS_PY3K */
   1006 
   1007 PyTypeObject membuf_object_type = {
   1008   PyVarObject_HEAD_INIT (NULL, 0)
   1009   "gdb.Membuf",			  /*tp_name*/
   1010   sizeof (membuf_object),	  /*tp_basicsize*/
   1011   0,				  /*tp_itemsize*/
   1012   mbpy_dealloc,			  /*tp_dealloc*/
   1013   0,				  /*tp_print*/
   1014   0,				  /*tp_getattr*/
   1015   0,				  /*tp_setattr*/
   1016   0,				  /*tp_compare*/
   1017   0,				  /*tp_repr*/
   1018   0,				  /*tp_as_number*/
   1019   0,				  /*tp_as_sequence*/
   1020   0,				  /*tp_as_mapping*/
   1021   0,				  /*tp_hash */
   1022   0,				  /*tp_call*/
   1023   mbpy_str,			  /*tp_str*/
   1024   0,				  /*tp_getattro*/
   1025   0,				  /*tp_setattro*/
   1026   &buffer_procs,		  /*tp_as_buffer*/
   1027   Py_TPFLAGS_DEFAULT,		  /*tp_flags*/
   1028   "GDB memory buffer object", 	  /*tp_doc*/
   1029   0,				  /* tp_traverse */
   1030   0,				  /* tp_clear */
   1031   0,				  /* tp_richcompare */
   1032   0,				  /* tp_weaklistoffset */
   1033   0,				  /* tp_iter */
   1034   0,				  /* tp_iternext */
   1035   0,				  /* tp_methods */
   1036   0,				  /* tp_members */
   1037   0,				  /* tp_getset */
   1038   0,				  /* tp_base */
   1039   0,				  /* tp_dict */
   1040   0,				  /* tp_descr_get */
   1041   0,				  /* tp_descr_set */
   1042   0,				  /* tp_dictoffset */
   1043   0,				  /* tp_init */
   1044   0,				  /* tp_alloc */
   1045 };
   1046