1 /* Python interface to inferiors.
3 Copyright (C) 2009-2013 Free Software Foundation, Inc.
5 This file is part of GDB.
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.
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.
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/>. */
21 #include "exceptions.h"
23 #include "gdbthread.h"
27 #include "python-internal.h"
28 #include "arch-utils.h"
30 #include "gdb_signals.h"
32 #include "py-stopevent.h"
34 struct threadlist_entry
{
35 thread_object
*thread_obj
;
36 struct threadlist_entry
*next
;
43 /* The inferior we represent. */
44 struct inferior
*inferior
;
46 /* thread_object instances under this inferior. This list owns a
47 reference to each object it contains. */
48 struct threadlist_entry
*threads
;
50 /* Number of threads in the list. */
54 static PyTypeObject inferior_object_type
55 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("inferior_object");
57 static const struct inferior_data
*infpy_inf_data_key
;
63 /* These are kept just for mbpy_str. */
68 static PyTypeObject membuf_object_type
69 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("membuf_object");
71 /* Require that INFERIOR be a valid inferior ID. */
72 #define INFPY_REQUIRE_VALID(Inferior) \
74 if (!Inferior->inferior) \
76 PyErr_SetString (PyExc_RuntimeError, \
77 _("Inferior no longer exists.")); \
83 python_on_normal_stop (struct bpstats
*bs
, int print_frame
)
85 struct cleanup
*cleanup
;
86 enum gdb_signal stop_signal
;
88 if (!gdb_python_initialized
)
91 if (!find_thread_ptid (inferior_ptid
))
94 stop_signal
= inferior_thread ()->suspend
.stop_signal
;
96 cleanup
= ensure_python_env (get_current_arch (), current_language
);
98 if (emit_stop_event (bs
, stop_signal
) < 0)
101 do_cleanups (cleanup
);
105 python_on_resume (ptid_t ptid
)
107 struct cleanup
*cleanup
;
109 if (!gdb_python_initialized
)
112 cleanup
= ensure_python_env (target_gdbarch (), current_language
);
114 if (emit_continue_event (ptid
) < 0)
115 gdbpy_print_stack ();
117 do_cleanups (cleanup
);
121 python_inferior_exit (struct inferior
*inf
)
123 struct cleanup
*cleanup
;
124 const LONGEST
*exit_code
= NULL
;
126 if (!gdb_python_initialized
)
129 cleanup
= ensure_python_env (target_gdbarch (), current_language
);
131 if (inf
->has_exit_code
)
132 exit_code
= &inf
->exit_code
;
134 if (emit_exited_event (exit_code
, inf
) < 0)
135 gdbpy_print_stack ();
137 do_cleanups (cleanup
);
140 /* Callback used to notify Python listeners about new objfiles loaded in the
144 python_new_objfile (struct objfile
*objfile
)
146 struct cleanup
*cleanup
;
151 if (!gdb_python_initialized
)
154 cleanup
= ensure_python_env (get_objfile_arch (objfile
), current_language
);
156 if (emit_new_objfile_event (objfile
) < 0)
157 gdbpy_print_stack ();
159 do_cleanups (cleanup
);
162 /* Return a reference to the Python object of type Inferior
163 representing INFERIOR. If the object has already been created,
164 return it and increment the reference count, otherwise, create it.
165 Return NULL on failure. */
167 inferior_to_inferior_object (struct inferior
*inferior
)
169 inferior_object
*inf_obj
;
171 inf_obj
= inferior_data (inferior
, infpy_inf_data_key
);
174 inf_obj
= PyObject_New (inferior_object
, &inferior_object_type
);
178 inf_obj
->inferior
= inferior
;
179 inf_obj
->threads
= NULL
;
180 inf_obj
->nthreads
= 0;
182 set_inferior_data (inferior
, infpy_inf_data_key
, inf_obj
);
186 Py_INCREF ((PyObject
*)inf_obj
);
188 return (PyObject
*) inf_obj
;
191 /* Finds the Python Inferior object for the given PID. Returns a
192 reference, or NULL if PID does not match any inferior object. */
195 find_inferior_object (int pid
)
197 struct inferior
*inf
= find_inferior_pid (pid
);
200 return inferior_to_inferior_object (inf
);
206 find_thread_object (ptid_t ptid
)
209 struct threadlist_entry
*thread
;
211 thread_object
*found
= NULL
;
213 pid
= ptid_get_pid (ptid
);
217 inf_obj
= find_inferior_object (pid
);
222 for (thread
= ((inferior_object
*)inf_obj
)->threads
; thread
;
223 thread
= thread
->next
)
224 if (ptid_equal (thread
->thread_obj
->thread
->ptid
, ptid
))
226 found
= thread
->thread_obj
;
239 add_thread_object (struct thread_info
*tp
)
241 struct cleanup
*cleanup
;
242 thread_object
*thread_obj
;
243 inferior_object
*inf_obj
;
244 struct threadlist_entry
*entry
;
246 if (!gdb_python_initialized
)
249 cleanup
= ensure_python_env (python_gdbarch
, python_language
);
251 thread_obj
= create_thread_object (tp
);
254 gdbpy_print_stack ();
255 do_cleanups (cleanup
);
259 inf_obj
= (inferior_object
*) thread_obj
->inf_obj
;
261 entry
= xmalloc (sizeof (struct threadlist_entry
));
262 entry
->thread_obj
= thread_obj
;
263 entry
->next
= inf_obj
->threads
;
265 inf_obj
->threads
= entry
;
268 do_cleanups (cleanup
);
272 delete_thread_object (struct thread_info
*tp
, int ignore
)
274 struct cleanup
*cleanup
;
275 inferior_object
*inf_obj
;
276 struct threadlist_entry
**entry
, *tmp
;
278 if (!gdb_python_initialized
)
281 cleanup
= ensure_python_env (python_gdbarch
, python_language
);
284 = (inferior_object
*) find_inferior_object (ptid_get_pid (tp
->ptid
));
287 do_cleanups (cleanup
);
291 /* Find thread entry in its inferior's thread_list. */
292 for (entry
= &inf_obj
->threads
; *entry
!= NULL
; entry
=
294 if ((*entry
)->thread_obj
->thread
== tp
)
300 do_cleanups (cleanup
);
305 tmp
->thread_obj
->thread
= NULL
;
307 *entry
= (*entry
)->next
;
310 Py_DECREF (tmp
->thread_obj
);
314 do_cleanups (cleanup
);
318 infpy_threads (PyObject
*self
, PyObject
*args
)
321 struct threadlist_entry
*entry
;
322 inferior_object
*inf_obj
= (inferior_object
*) self
;
324 volatile struct gdb_exception except
;
326 INFPY_REQUIRE_VALID (inf_obj
);
328 TRY_CATCH (except
, RETURN_MASK_ALL
)
329 update_thread_list ();
330 GDB_PY_HANDLE_EXCEPTION (except
);
332 tuple
= PyTuple_New (inf_obj
->nthreads
);
336 for (i
= 0, entry
= inf_obj
->threads
; i
< inf_obj
->nthreads
;
337 i
++, entry
= entry
->next
)
339 Py_INCREF (entry
->thread_obj
);
340 PyTuple_SET_ITEM (tuple
, i
, (PyObject
*) entry
->thread_obj
);
347 infpy_get_num (PyObject
*self
, void *closure
)
349 inferior_object
*inf
= (inferior_object
*) self
;
351 INFPY_REQUIRE_VALID (inf
);
353 return PyLong_FromLong (inf
->inferior
->num
);
357 infpy_get_pid (PyObject
*self
, void *closure
)
359 inferior_object
*inf
= (inferior_object
*) self
;
361 INFPY_REQUIRE_VALID (inf
);
363 return PyLong_FromLong (inf
->inferior
->pid
);
367 infpy_get_was_attached (PyObject
*self
, void *closure
)
369 inferior_object
*inf
= (inferior_object
*) self
;
371 INFPY_REQUIRE_VALID (inf
);
372 if (inf
->inferior
->attach_flag
)
378 build_inferior_list (struct inferior
*inf
, void *arg
)
380 PyObject
*list
= arg
;
381 PyObject
*inferior
= inferior_to_inferior_object (inf
);
387 success
= PyList_Append (list
, inferior
);
388 Py_DECREF (inferior
);
396 /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
397 Returns a tuple of all inferiors. */
399 gdbpy_inferiors (PyObject
*unused
, PyObject
*unused2
)
401 PyObject
*list
, *tuple
;
403 list
= PyList_New (0);
407 if (iterate_over_inferiors (build_inferior_list
, list
))
413 tuple
= PyList_AsTuple (list
);
419 /* Membuf and memory manipulation. */
421 /* Implementation of Inferior.read_memory (address, length).
422 Returns a Python buffer object with LENGTH bytes of the inferior's
423 memory at ADDRESS. Both arguments are integers. Returns NULL on error,
424 with a python exception set. */
426 infpy_read_memory (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
428 CORE_ADDR addr
, length
;
430 membuf_object
*membuf_obj
;
431 PyObject
*addr_obj
, *length_obj
, *result
;
432 volatile struct gdb_exception except
;
433 static char *keywords
[] = { "address", "length", NULL
};
435 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "OO", keywords
,
436 &addr_obj
, &length_obj
))
439 if (get_addr_from_python (addr_obj
, &addr
) < 0
440 || get_addr_from_python (length_obj
, &length
) < 0)
443 TRY_CATCH (except
, RETURN_MASK_ALL
)
445 buffer
= xmalloc (length
);
447 read_memory (addr
, buffer
, length
);
449 if (except
.reason
< 0)
452 GDB_PY_HANDLE_EXCEPTION (except
);
455 membuf_obj
= PyObject_New (membuf_object
, &membuf_object_type
);
456 if (membuf_obj
== NULL
)
462 membuf_obj
->buffer
= buffer
;
463 membuf_obj
->addr
= addr
;
464 membuf_obj
->length
= length
;
467 result
= PyMemoryView_FromObject ((PyObject
*) membuf_obj
);
469 result
= PyBuffer_FromReadWriteObject ((PyObject
*) membuf_obj
, 0,
472 Py_DECREF (membuf_obj
);
477 /* Implementation of Inferior.write_memory (address, buffer [, length]).
478 Writes the contents of BUFFER (a Python object supporting the read
479 buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
480 bytes from BUFFER, or its entire contents if the argument is not
481 provided. The function returns nothing. Returns NULL on error, with
482 a python exception set. */
484 infpy_write_memory (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
488 CORE_ADDR addr
, length
;
489 PyObject
*addr_obj
, *length_obj
= NULL
;
490 volatile struct gdb_exception except
;
491 static char *keywords
[] = { "address", "buffer", "length", NULL
};
495 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "Os*|O", keywords
,
503 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "Os#|O", keywords
,
504 &addr_obj
, &buffer
, &buf_len
,
509 if (get_addr_from_python (addr_obj
, &addr
) < 0)
514 else if (get_addr_from_python (length_obj
, &length
) < 0)
517 TRY_CATCH (except
, RETURN_MASK_ALL
)
519 write_memory_with_notification (addr
, (gdb_byte
*) buffer
, length
);
522 PyBuffer_Release (&pybuf
);
524 GDB_PY_HANDLE_EXCEPTION (except
);
530 PyBuffer_Release (&pybuf
);
535 /* Destructor of Membuf objects. */
537 mbpy_dealloc (PyObject
*self
)
539 xfree (((membuf_object
*) self
)->buffer
);
540 Py_TYPE (self
)->tp_free (self
);
543 /* Return a description of the Membuf object. */
545 mbpy_str (PyObject
*self
)
547 membuf_object
*membuf_obj
= (membuf_object
*) self
;
549 return PyString_FromFormat (_("Memory buffer for address %s, \
550 which is %s bytes long."),
551 paddress (python_gdbarch
, membuf_obj
->addr
),
552 pulongest (membuf_obj
->length
));
558 get_buffer (PyObject
*self
, Py_buffer
*buf
, int flags
)
560 membuf_object
*membuf_obj
= (membuf_object
*) self
;
563 ret
= PyBuffer_FillInfo (buf
, self
, membuf_obj
->buffer
,
564 membuf_obj
->length
, 0,
574 get_read_buffer (PyObject
*self
, Py_ssize_t segment
, void **ptrptr
)
576 membuf_object
*membuf_obj
= (membuf_object
*) self
;
580 PyErr_SetString (PyExc_SystemError
,
581 _("The memory buffer supports only one segment."));
585 *ptrptr
= membuf_obj
->buffer
;
587 return membuf_obj
->length
;
591 get_write_buffer (PyObject
*self
, Py_ssize_t segment
, void **ptrptr
)
593 return get_read_buffer (self
, segment
, ptrptr
);
597 get_seg_count (PyObject
*self
, Py_ssize_t
*lenp
)
600 *lenp
= ((membuf_object
*) self
)->length
;
606 get_char_buffer (PyObject
*self
, Py_ssize_t segment
, char **ptrptr
)
611 ret
= get_read_buffer (self
, segment
, &ptr
);
612 *ptrptr
= (char *) ptr
;
620 gdb.search_memory (address, length, pattern). ADDRESS is the
621 address to start the search. LENGTH specifies the scope of the
622 search from ADDRESS. PATTERN is the pattern to search for (and
623 must be a Python object supporting the buffer protocol).
624 Returns a Python Long object holding the address where the pattern
625 was located, or if the pattern was not found, returns None. Returns NULL
626 on error, with a python exception set. */
628 infpy_search_memory (PyObject
*self
, PyObject
*args
, PyObject
*kw
)
630 CORE_ADDR start_addr
, length
;
631 static char *keywords
[] = { "address", "length", "pattern", NULL
};
632 PyObject
*start_addr_obj
, *length_obj
;
633 volatile struct gdb_exception except
;
634 Py_ssize_t pattern_size
;
636 CORE_ADDR found_addr
;
641 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "OOs*", keywords
,
642 &start_addr_obj
, &length_obj
,
647 pattern_size
= pybuf
.len
;
651 if (! PyArg_ParseTupleAndKeywords (args
, kw
, "OOO", keywords
,
652 &start_addr_obj
, &length_obj
,
656 if (!PyObject_CheckReadBuffer (pattern
))
658 PyErr_SetString (PyExc_RuntimeError
,
659 _("The pattern is not a Python buffer."));
664 if (PyObject_AsReadBuffer (pattern
, &buffer
, &pattern_size
) == -1)
668 if (get_addr_from_python (start_addr_obj
, &start_addr
) < 0)
671 if (get_addr_from_python (length_obj
, &length
) < 0)
676 PyErr_SetString (PyExc_ValueError
,
677 _("Search range is empty."));
680 /* Watch for overflows. */
681 else if (length
> CORE_ADDR_MAX
682 || (start_addr
+ length
- 1) < start_addr
)
684 PyErr_SetString (PyExc_ValueError
,
685 _("The search range is too large."));
689 TRY_CATCH (except
, RETURN_MASK_ALL
)
691 found
= target_search_memory (start_addr
, length
,
692 buffer
, pattern_size
,
696 PyBuffer_Release (&pybuf
);
698 GDB_PY_HANDLE_EXCEPTION (except
);
701 return PyLong_FromLong (found_addr
);
707 PyBuffer_Release (&pybuf
);
712 /* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
713 Returns True if this inferior object still exists in GDB. */
716 infpy_is_valid (PyObject
*self
, PyObject
*args
)
718 inferior_object
*inf
= (inferior_object
*) self
;
727 infpy_dealloc (PyObject
*obj
)
729 inferior_object
*inf_obj
= (inferior_object
*) obj
;
730 struct inferior
*inf
= inf_obj
->inferior
;
735 set_inferior_data (inf
, infpy_inf_data_key
, NULL
);
738 /* Clear the INFERIOR pointer in an Inferior object and clear the
741 py_free_inferior (struct inferior
*inf
, void *datum
)
744 struct cleanup
*cleanup
;
745 inferior_object
*inf_obj
= datum
;
746 struct threadlist_entry
*th_entry
, *th_tmp
;
748 if (!gdb_python_initialized
)
751 cleanup
= ensure_python_env (python_gdbarch
, python_language
);
753 inf_obj
->inferior
= NULL
;
755 /* Deallocate threads list. */
756 for (th_entry
= inf_obj
->threads
; th_entry
!= NULL
;)
758 Py_DECREF (th_entry
->thread_obj
);
761 th_entry
= th_entry
->next
;
765 inf_obj
->nthreads
= 0;
767 Py_DECREF ((PyObject
*) inf_obj
);
768 do_cleanups (cleanup
);
771 /* Implementation of gdb.selected_inferior() -> gdb.Inferior.
772 Returns the current inferior object. */
775 gdbpy_selected_inferior (PyObject
*self
, PyObject
*args
)
777 return inferior_to_inferior_object (current_inferior ());
781 gdbpy_initialize_inferior (void)
783 if (PyType_Ready (&inferior_object_type
) < 0)
786 if (gdb_pymodule_addobject (gdb_module
, "Inferior",
787 (PyObject
*) &inferior_object_type
) < 0)
791 register_inferior_data_with_cleanup (NULL
, py_free_inferior
);
793 observer_attach_new_thread (add_thread_object
);
794 observer_attach_thread_exit (delete_thread_object
);
795 observer_attach_normal_stop (python_on_normal_stop
);
796 observer_attach_target_resumed (python_on_resume
);
797 observer_attach_inferior_exit (python_inferior_exit
);
798 observer_attach_new_objfile (python_new_objfile
);
800 membuf_object_type
.tp_new
= PyType_GenericNew
;
801 if (PyType_Ready (&membuf_object_type
) < 0)
804 return gdb_pymodule_addobject (gdb_module
, "Membuf", (PyObject
*)
805 &membuf_object_type
);
808 static PyGetSetDef inferior_object_getset
[] =
810 { "num", infpy_get_num
, NULL
, "ID of inferior, as assigned by GDB.", NULL
},
811 { "pid", infpy_get_pid
, NULL
, "PID of inferior, as assigned by the OS.",
813 { "was_attached", infpy_get_was_attached
, NULL
,
814 "True if the inferior was created using 'attach'.", NULL
},
818 static PyMethodDef inferior_object_methods
[] =
820 { "is_valid", infpy_is_valid
, METH_NOARGS
,
821 "is_valid () -> Boolean.\n\
822 Return true if this inferior is valid, false if not." },
823 { "threads", infpy_threads
, METH_NOARGS
,
824 "Return all the threads of this inferior." },
825 { "read_memory", (PyCFunction
) infpy_read_memory
,
826 METH_VARARGS
| METH_KEYWORDS
,
827 "read_memory (address, length) -> buffer\n\
828 Return a buffer object for reading from the inferior's memory." },
829 { "write_memory", (PyCFunction
) infpy_write_memory
,
830 METH_VARARGS
| METH_KEYWORDS
,
831 "write_memory (address, buffer [, length])\n\
832 Write the given buffer object to the inferior's memory." },
833 { "search_memory", (PyCFunction
) infpy_search_memory
,
834 METH_VARARGS
| METH_KEYWORDS
,
835 "search_memory (address, length, pattern) -> long\n\
836 Return a long with the address of a match, or None." },
840 static PyTypeObject inferior_object_type
=
842 PyVarObject_HEAD_INIT (NULL
, 0)
843 "gdb.Inferior", /* tp_name */
844 sizeof (inferior_object
), /* tp_basicsize */
846 infpy_dealloc
, /* tp_dealloc */
852 0, /* tp_as_number */
853 0, /* tp_as_sequence */
854 0, /* tp_as_mapping */
860 0, /* tp_as_buffer */
861 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_HAVE_ITER
, /* tp_flags */
862 "GDB inferior object", /* tp_doc */
865 0, /* tp_richcompare */
866 0, /* tp_weaklistoffset */
869 inferior_object_methods
, /* tp_methods */
871 inferior_object_getset
, /* tp_getset */
874 0, /* tp_descr_get */
875 0, /* tp_descr_set */
876 0, /* tp_dictoffset */
883 static PyBufferProcs buffer_procs
=
890 /* Python doesn't provide a decent way to get compatibility here. */
891 #if HAVE_LIBPYTHON2_4
892 #define CHARBUFFERPROC_NAME getcharbufferproc
894 #define CHARBUFFERPROC_NAME charbufferproc
897 static PyBufferProcs buffer_procs
= {
901 /* The cast here works around a difference between Python 2.4 and
903 (CHARBUFFERPROC_NAME
) get_char_buffer
907 static PyTypeObject membuf_object_type
= {
908 PyVarObject_HEAD_INIT (NULL
, 0)
909 "gdb.Membuf", /*tp_name*/
910 sizeof (membuf_object
), /*tp_basicsize*/
912 mbpy_dealloc
, /*tp_dealloc*/
919 0, /*tp_as_sequence*/
926 &buffer_procs
, /*tp_as_buffer*/
927 Py_TPFLAGS_DEFAULT
, /*tp_flags*/
928 "GDB memory buffer object", /*tp_doc*/
931 0, /* tp_richcompare */
932 0, /* tp_weaklistoffset */
940 0, /* tp_descr_get */
941 0, /* tp_descr_set */
942 0, /* tp_dictoffset */