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