1 /* Python interface to inferiors.
3 Copyright (C) 2009-2017 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/>. */
22 #include "gdbthread.h"
26 #include "python-internal.h"
27 #include "arch-utils.h"
29 #include "gdb_signals.h"
31 #include "py-stopevent.h"
33 struct threadlist_entry {
34 thread_object *thread_obj;
35 struct threadlist_entry *next;
42 /* The inferior we represent. */
43 struct inferior *inferior;
45 /* thread_object instances under this inferior. This list owns a
46 reference to each object it contains. */
47 struct threadlist_entry *threads;
49 /* Number of threads in the list. */
53 extern PyTypeObject inferior_object_type
54 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("inferior_object");
56 static const struct inferior_data *infpy_inf_data_key;
62 /* These are kept just for mbpy_str. */
67 extern PyTypeObject membuf_object_type
68 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("membuf_object");
70 /* Require that INFERIOR be a valid inferior ID. */
71 #define INFPY_REQUIRE_VALID(Inferior) \
73 if (!Inferior->inferior) \
75 PyErr_SetString (PyExc_RuntimeError, \
76 _("Inferior no longer exists.")); \
82 python_on_normal_stop (struct bpstats *bs, int print_frame)
84 enum gdb_signal stop_signal;
86 if (!gdb_python_initialized)
89 if (!find_thread_ptid (inferior_ptid))
92 stop_signal = inferior_thread ()->suspend.stop_signal;
94 gdbpy_enter enter_py (get_current_arch (), current_language);
96 if (emit_stop_event (bs, stop_signal) < 0)
101 python_on_resume (ptid_t ptid)
103 if (!gdb_python_initialized)
106 gdbpy_enter enter_py (target_gdbarch (), current_language);
108 if (emit_continue_event (ptid) < 0)
109 gdbpy_print_stack ();
112 /* Callback, registered as an observer, that notifies Python listeners
113 when an inferior function call is about to be made. */
116 python_on_inferior_call_pre (ptid_t thread, CORE_ADDR address)
118 gdbpy_enter enter_py (target_gdbarch (), current_language);
120 if (emit_inferior_call_event (INFERIOR_CALL_PRE, thread, address) < 0)
121 gdbpy_print_stack ();
124 /* Callback, registered as an observer, that notifies Python listeners
125 when an inferior function call has completed. */
128 python_on_inferior_call_post (ptid_t thread, CORE_ADDR address)
130 gdbpy_enter enter_py (target_gdbarch (), current_language);
132 if (emit_inferior_call_event (INFERIOR_CALL_POST, thread, address) < 0)
133 gdbpy_print_stack ();
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
141 python_on_memory_change (struct inferior *inferior, CORE_ADDR addr, ssize_t len, const bfd_byte *data)
143 gdbpy_enter enter_py (target_gdbarch (), current_language);
145 if (emit_memory_changed_event (addr, len) < 0)
146 gdbpy_print_stack ();
149 /* Callback, registered as an observer, that notifies Python listeners
150 when a register has been modified by user action (eg via a 'set'
154 python_on_register_change (struct frame_info *frame, int regnum)
156 gdbpy_enter enter_py (target_gdbarch (), current_language);
158 if (emit_register_changed_event (frame, regnum) < 0)
159 gdbpy_print_stack ();
163 python_inferior_exit (struct inferior *inf)
165 const LONGEST *exit_code = NULL;
167 if (!gdb_python_initialized)
170 gdbpy_enter enter_py (target_gdbarch (), current_language);
172 if (inf->has_exit_code)
173 exit_code = &inf->exit_code;
175 if (emit_exited_event (exit_code, inf) < 0)
176 gdbpy_print_stack ();
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). */
184 python_new_objfile (struct objfile *objfile)
186 if (!gdb_python_initialized)
189 gdbpy_enter enter_py (objfile != NULL
190 ? get_objfile_arch (objfile)
196 if (emit_clear_objfiles_event () < 0)
197 gdbpy_print_stack ();
201 if (emit_new_objfile_event (objfile) < 0)
202 gdbpy_print_stack ();
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. */
211 inferior_to_inferior_object (struct inferior *inferior)
213 inferior_object *inf_obj;
215 inf_obj = (inferior_object *) inferior_data (inferior, infpy_inf_data_key);
218 inf_obj = PyObject_New (inferior_object, &inferior_object_type);
222 inf_obj->inferior = inferior;
223 inf_obj->threads = NULL;
224 inf_obj->nthreads = 0;
226 set_inferior_data (inferior, infpy_inf_data_key, inf_obj);
230 Py_INCREF ((PyObject *)inf_obj);
232 return (PyObject *) inf_obj;
235 /* Finds the Python Inferior object for the given PID. Returns a
236 reference, or NULL if PID does not match any inferior object. */
239 find_inferior_object (int pid)
241 struct inferior *inf = find_inferior_pid (pid);
244 return inferior_to_inferior_object (inf);
250 find_thread_object (ptid_t ptid)
253 struct threadlist_entry *thread;
255 pid = ptid_get_pid (ptid);
259 gdbpy_ref<> inf_obj (find_inferior_object (pid));
263 for (thread = ((inferior_object *)(inf_obj.get ()))->threads; thread;
264 thread = thread->next)
265 if (ptid_equal (thread->thread_obj->thread->ptid, ptid))
266 return thread->thread_obj;
272 add_thread_object (struct thread_info *tp)
274 thread_object *thread_obj;
275 inferior_object *inf_obj;
276 struct threadlist_entry *entry;
278 if (!gdb_python_initialized)
281 gdbpy_enter enter_py (python_gdbarch, python_language);
283 thread_obj = create_thread_object (tp);
286 gdbpy_print_stack ();
290 inf_obj = (inferior_object *) thread_obj->inf_obj;
292 entry = XNEW (struct threadlist_entry);
293 entry->thread_obj = thread_obj;
294 entry->next = inf_obj->threads;
296 inf_obj->threads = entry;
301 delete_thread_object (struct thread_info *tp, int ignore)
303 inferior_object *inf_obj;
304 struct threadlist_entry **entry, *tmp;
306 if (!gdb_python_initialized)
309 gdbpy_enter enter_py (python_gdbarch, python_language);
312 = (inferior_object *) find_inferior_object (ptid_get_pid (tp->ptid));
316 /* Find thread entry in its inferior's thread_list. */
317 for (entry = &inf_obj->threads; *entry != NULL; entry =
319 if ((*entry)->thread_obj->thread == tp)
329 tmp->thread_obj->thread = NULL;
331 *entry = (*entry)->next;
334 Py_DECREF (tmp->thread_obj);
340 infpy_threads (PyObject *self, PyObject *args)
343 struct threadlist_entry *entry;
344 inferior_object *inf_obj = (inferior_object *) self;
347 INFPY_REQUIRE_VALID (inf_obj);
351 update_thread_list ();
353 CATCH (except, RETURN_MASK_ALL)
355 GDB_PY_HANDLE_EXCEPTION (except);
359 tuple = PyTuple_New (inf_obj->nthreads);
363 for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
364 i++, entry = entry->next)
366 Py_INCREF (entry->thread_obj);
367 PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
374 infpy_get_num (PyObject *self, void *closure)
376 inferior_object *inf = (inferior_object *) self;
378 INFPY_REQUIRE_VALID (inf);
380 return PyLong_FromLong (inf->inferior->num);
384 infpy_get_pid (PyObject *self, void *closure)
386 inferior_object *inf = (inferior_object *) self;
388 INFPY_REQUIRE_VALID (inf);
390 return PyLong_FromLong (inf->inferior->pid);
394 infpy_get_was_attached (PyObject *self, void *closure)
396 inferior_object *inf = (inferior_object *) self;
398 INFPY_REQUIRE_VALID (inf);
399 if (inf->inferior->attach_flag)
405 build_inferior_list (struct inferior *inf, void *arg)
407 PyObject *list = (PyObject *) arg;
408 gdbpy_ref<> inferior (inferior_to_inferior_object (inf));
410 if (inferior == NULL)
413 return PyList_Append (list, inferior.get ()) ? 1 : 0;
416 /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
417 Returns a tuple of all inferiors. */
419 gdbpy_inferiors (PyObject *unused, PyObject *unused2)
421 gdbpy_ref<> list (PyList_New (0));
425 if (iterate_over_inferiors (build_inferior_list, list.get ()))
428 return PyList_AsTuple (list.get ());
431 /* Membuf and memory manipulation. */
433 /* Implementation of Inferior.read_memory (address, length).
434 Returns a Python buffer object with LENGTH bytes of the inferior's
435 memory at ADDRESS. Both arguments are integers. Returns NULL on error,
436 with a python exception set. */
438 infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
440 CORE_ADDR addr, length;
441 gdb_byte *buffer = NULL;
442 membuf_object *membuf_obj;
443 PyObject *addr_obj, *length_obj, *result;
444 static char *keywords[] = { "address", "length", NULL };
446 if (! PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
447 &addr_obj, &length_obj))
450 if (get_addr_from_python (addr_obj, &addr) < 0
451 || get_addr_from_python (length_obj, &length) < 0)
456 buffer = (gdb_byte *) xmalloc (length);
458 read_memory (addr, buffer, length);
460 CATCH (except, RETURN_MASK_ALL)
463 GDB_PY_HANDLE_EXCEPTION (except);
467 membuf_obj = PyObject_New (membuf_object, &membuf_object_type);
468 if (membuf_obj == NULL)
474 membuf_obj->buffer = buffer;
475 membuf_obj->addr = addr;
476 membuf_obj->length = length;
479 result = PyMemoryView_FromObject ((PyObject *) membuf_obj);
481 result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
484 Py_DECREF (membuf_obj);
489 /* Implementation of Inferior.write_memory (address, buffer [, length]).
490 Writes the contents of BUFFER (a Python object supporting the read
491 buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
492 bytes from BUFFER, or its entire contents if the argument is not
493 provided. The function returns nothing. Returns NULL on error, with
494 a python exception set. */
496 infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
498 struct gdb_exception except = exception_none;
500 const gdb_byte *buffer;
501 CORE_ADDR addr, length;
502 PyObject *addr_obj, *length_obj = NULL;
503 static char *keywords[] = { "address", "buffer", "length", NULL };
507 if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
512 buffer = (const gdb_byte *) pybuf.buf;
515 if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
516 &addr_obj, &buffer, &buf_len,
520 buffer = (const gdb_byte *) buffer;
523 if (get_addr_from_python (addr_obj, &addr) < 0)
528 else if (get_addr_from_python (length_obj, &length) < 0)
533 write_memory_with_notification (addr, buffer, length);
535 CATCH (ex, RETURN_MASK_ALL)
542 PyBuffer_Release (&pybuf);
544 GDB_PY_HANDLE_EXCEPTION (except);
550 PyBuffer_Release (&pybuf);
555 /* Destructor of Membuf objects. */
557 mbpy_dealloc (PyObject *self)
559 xfree (((membuf_object *) self)->buffer);
560 Py_TYPE (self)->tp_free (self);
563 /* Return a description of the Membuf object. */
565 mbpy_str (PyObject *self)
567 membuf_object *membuf_obj = (membuf_object *) self;
569 return PyString_FromFormat (_("Memory buffer for address %s, \
570 which is %s bytes long."),
571 paddress (python_gdbarch, membuf_obj->addr),
572 pulongest (membuf_obj->length));
578 get_buffer (PyObject *self, Py_buffer *buf, int flags)
580 membuf_object *membuf_obj = (membuf_object *) self;
583 ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer,
584 membuf_obj->length, 0,
594 get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
596 membuf_object *membuf_obj = (membuf_object *) self;
600 PyErr_SetString (PyExc_SystemError,
601 _("The memory buffer supports only one segment."));
605 *ptrptr = membuf_obj->buffer;
607 return membuf_obj->length;
611 get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
613 return get_read_buffer (self, segment, ptrptr);
617 get_seg_count (PyObject *self, Py_ssize_t *lenp)
620 *lenp = ((membuf_object *) self)->length;
626 get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
631 ret = get_read_buffer (self, segment, &ptr);
632 *ptrptr = (char *) ptr;
640 gdb.search_memory (address, length, pattern). ADDRESS is the
641 address to start the search. LENGTH specifies the scope of the
642 search from ADDRESS. PATTERN is the pattern to search for (and
643 must be a Python object supporting the buffer protocol).
644 Returns a Python Long object holding the address where the pattern
645 was located, or if the pattern was not found, returns None. Returns NULL
646 on error, with a python exception set. */
648 infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
650 struct gdb_exception except = exception_none;
651 CORE_ADDR start_addr, length;
652 static char *keywords[] = { "address", "length", "pattern", NULL };
653 PyObject *start_addr_obj, *length_obj;
654 Py_ssize_t pattern_size;
655 const gdb_byte *buffer;
656 CORE_ADDR found_addr;
661 if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
662 &start_addr_obj, &length_obj,
666 buffer = (const gdb_byte *) pybuf.buf;
667 pattern_size = pybuf.len;
672 if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
673 &start_addr_obj, &length_obj,
677 if (!PyObject_CheckReadBuffer (pattern))
679 PyErr_SetString (PyExc_RuntimeError,
680 _("The pattern is not a Python buffer."));
685 if (PyObject_AsReadBuffer (pattern, &vbuffer, &pattern_size) == -1)
688 buffer = (const gdb_byte *) vbuffer;
691 if (get_addr_from_python (start_addr_obj, &start_addr) < 0)
694 if (get_addr_from_python (length_obj, &length) < 0)
699 PyErr_SetString (PyExc_ValueError,
700 _("Search range is empty."));
703 /* Watch for overflows. */
704 else if (length > CORE_ADDR_MAX
705 || (start_addr + length - 1) < start_addr)
707 PyErr_SetString (PyExc_ValueError,
708 _("The search range is too large."));
714 found = target_search_memory (start_addr, length,
715 buffer, pattern_size,
718 CATCH (ex, RETURN_MASK_ALL)
725 PyBuffer_Release (&pybuf);
727 GDB_PY_HANDLE_EXCEPTION (except);
730 return PyLong_FromLong (found_addr);
736 PyBuffer_Release (&pybuf);
741 /* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
742 Returns True if this inferior object still exists in GDB. */
745 infpy_is_valid (PyObject *self, PyObject *args)
747 inferior_object *inf = (inferior_object *) self;
756 infpy_dealloc (PyObject *obj)
758 inferior_object *inf_obj = (inferior_object *) obj;
759 struct inferior *inf = inf_obj->inferior;
764 set_inferior_data (inf, infpy_inf_data_key, NULL);
767 /* Clear the INFERIOR pointer in an Inferior object and clear the
770 py_free_inferior (struct inferior *inf, void *datum)
772 inferior_object *inf_obj = (inferior_object *) datum;
773 struct threadlist_entry *th_entry, *th_tmp;
775 if (!gdb_python_initialized)
778 gdbpy_enter enter_py (python_gdbarch, python_language);
780 inf_obj->inferior = NULL;
782 /* Deallocate threads list. */
783 for (th_entry = inf_obj->threads; th_entry != NULL;)
785 Py_DECREF (th_entry->thread_obj);
788 th_entry = th_entry->next;
792 inf_obj->nthreads = 0;
794 Py_DECREF ((PyObject *) inf_obj);
797 /* Implementation of gdb.selected_inferior() -> gdb.Inferior.
798 Returns the current inferior object. */
801 gdbpy_selected_inferior (PyObject *self, PyObject *args)
803 return inferior_to_inferior_object (current_inferior ());
807 gdbpy_initialize_inferior (void)
809 if (PyType_Ready (&inferior_object_type) < 0)
812 if (gdb_pymodule_addobject (gdb_module, "Inferior",
813 (PyObject *) &inferior_object_type) < 0)
817 register_inferior_data_with_cleanup (NULL, py_free_inferior);
819 observer_attach_new_thread (add_thread_object);
820 observer_attach_thread_exit (delete_thread_object);
821 observer_attach_normal_stop (python_on_normal_stop);
822 observer_attach_target_resumed (python_on_resume);
823 observer_attach_inferior_call_pre (python_on_inferior_call_pre);
824 observer_attach_inferior_call_post (python_on_inferior_call_post);
825 observer_attach_memory_changed (python_on_memory_change);
826 observer_attach_register_changed (python_on_register_change);
827 observer_attach_inferior_exit (python_inferior_exit);
828 observer_attach_new_objfile (python_new_objfile);
830 membuf_object_type.tp_new = PyType_GenericNew;
831 if (PyType_Ready (&membuf_object_type) < 0)
834 return gdb_pymodule_addobject (gdb_module, "Membuf", (PyObject *)
835 &membuf_object_type);
838 static PyGetSetDef inferior_object_getset[] =
840 { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
841 { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
843 { "was_attached", infpy_get_was_attached, NULL,
844 "True if the inferior was created using 'attach'.", NULL },
848 static PyMethodDef inferior_object_methods[] =
850 { "is_valid", infpy_is_valid, METH_NOARGS,
851 "is_valid () -> Boolean.\n\
852 Return true if this inferior is valid, false if not." },
853 { "threads", infpy_threads, METH_NOARGS,
854 "Return all the threads of this inferior." },
855 { "read_memory", (PyCFunction) infpy_read_memory,
856 METH_VARARGS | METH_KEYWORDS,
857 "read_memory (address, length) -> buffer\n\
858 Return a buffer object for reading from the inferior's memory." },
859 { "write_memory", (PyCFunction) infpy_write_memory,
860 METH_VARARGS | METH_KEYWORDS,
861 "write_memory (address, buffer [, length])\n\
862 Write the given buffer object to the inferior's memory." },
863 { "search_memory", (PyCFunction) infpy_search_memory,
864 METH_VARARGS | METH_KEYWORDS,
865 "search_memory (address, length, pattern) -> long\n\
866 Return a long with the address of a match, or None." },
870 PyTypeObject inferior_object_type =
872 PyVarObject_HEAD_INIT (NULL, 0)
873 "gdb.Inferior", /* tp_name */
874 sizeof (inferior_object), /* tp_basicsize */
876 infpy_dealloc, /* tp_dealloc */
882 0, /* tp_as_number */
883 0, /* tp_as_sequence */
884 0, /* tp_as_mapping */
890 0, /* tp_as_buffer */
891 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags */
892 "GDB inferior object", /* tp_doc */
895 0, /* tp_richcompare */
896 0, /* tp_weaklistoffset */
899 inferior_object_methods, /* tp_methods */
901 inferior_object_getset, /* tp_getset */
904 0, /* tp_descr_get */
905 0, /* tp_descr_set */
906 0, /* tp_dictoffset */
913 static PyBufferProcs buffer_procs =
920 /* Python doesn't provide a decent way to get compatibility here. */
921 #if HAVE_LIBPYTHON2_4
922 #define CHARBUFFERPROC_NAME getcharbufferproc
924 #define CHARBUFFERPROC_NAME charbufferproc
927 static PyBufferProcs buffer_procs = {
931 /* The cast here works around a difference between Python 2.4 and
933 (CHARBUFFERPROC_NAME) get_char_buffer
937 PyTypeObject membuf_object_type = {
938 PyVarObject_HEAD_INIT (NULL, 0)
939 "gdb.Membuf", /*tp_name*/
940 sizeof (membuf_object), /*tp_basicsize*/
942 mbpy_dealloc, /*tp_dealloc*/
949 0, /*tp_as_sequence*/
956 &buffer_procs, /*tp_as_buffer*/
957 Py_TPFLAGS_DEFAULT, /*tp_flags*/
958 "GDB memory buffer object", /*tp_doc*/
961 0, /* tp_richcompare */
962 0, /* tp_weaklistoffset */
970 0, /* tp_descr_get */
971 0, /* tp_descr_set */
972 0, /* tp_dictoffset */