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 (!find_thread_ptid (inferior_ptid))
91 stop_signal = inferior_thread ()->suspend.stop_signal;
93 cleanup = ensure_python_env (get_current_arch (), current_language);
95 if (emit_stop_event (bs, stop_signal) < 0)
98 do_cleanups (cleanup);
102 python_on_resume (ptid_t ptid)
104 struct cleanup *cleanup;
106 cleanup = ensure_python_env (target_gdbarch (), current_language);
108 if (emit_continue_event (ptid) < 0)
109 gdbpy_print_stack ();
111 do_cleanups (cleanup);
115 python_inferior_exit (struct inferior *inf)
117 struct cleanup *cleanup;
118 const LONGEST *exit_code = NULL;
120 cleanup = ensure_python_env (target_gdbarch (), current_language);
122 if (inf->has_exit_code)
123 exit_code = &inf->exit_code;
125 if (emit_exited_event (exit_code, inf) < 0)
126 gdbpy_print_stack ();
128 do_cleanups (cleanup);
131 /* Callback used to notify Python listeners about new objfiles loaded in the
135 python_new_objfile (struct objfile *objfile)
137 struct cleanup *cleanup;
142 cleanup = ensure_python_env (get_objfile_arch (objfile), current_language);
144 if (emit_new_objfile_event (objfile) < 0)
145 gdbpy_print_stack ();
147 do_cleanups (cleanup);
150 /* Return a reference to the Python object of type Inferior
151 representing INFERIOR. If the object has already been created,
152 return it and increment the reference count, otherwise, create it.
153 Return NULL on failure. */
155 inferior_to_inferior_object (struct inferior *inferior)
157 inferior_object *inf_obj;
159 inf_obj = inferior_data (inferior, infpy_inf_data_key);
162 inf_obj = PyObject_New (inferior_object, &inferior_object_type);
166 inf_obj->inferior = inferior;
167 inf_obj->threads = NULL;
168 inf_obj->nthreads = 0;
170 set_inferior_data (inferior, infpy_inf_data_key, inf_obj);
174 Py_INCREF ((PyObject *)inf_obj);
176 return (PyObject *) inf_obj;
179 /* Finds the Python Inferior object for the given PID. Returns a
180 reference, or NULL if PID does not match any inferior object. */
183 find_inferior_object (int pid)
185 struct inferior *inf = find_inferior_pid (pid);
188 return inferior_to_inferior_object (inf);
194 find_thread_object (ptid_t ptid)
197 struct threadlist_entry *thread;
199 thread_object *found = NULL;
205 inf_obj = find_inferior_object (pid);
210 for (thread = ((inferior_object *)inf_obj)->threads; thread;
211 thread = thread->next)
212 if (ptid_equal (thread->thread_obj->thread->ptid, ptid))
214 found = thread->thread_obj;
227 add_thread_object (struct thread_info *tp)
229 struct cleanup *cleanup;
230 thread_object *thread_obj;
231 inferior_object *inf_obj;
232 struct threadlist_entry *entry;
234 cleanup = ensure_python_env (python_gdbarch, python_language);
236 thread_obj = create_thread_object (tp);
239 gdbpy_print_stack ();
240 do_cleanups (cleanup);
244 inf_obj = (inferior_object *) thread_obj->inf_obj;
246 entry = xmalloc (sizeof (struct threadlist_entry));
247 entry->thread_obj = thread_obj;
248 entry->next = inf_obj->threads;
250 inf_obj->threads = entry;
253 do_cleanups (cleanup);
257 delete_thread_object (struct thread_info *tp, int ignore)
259 struct cleanup *cleanup;
260 inferior_object *inf_obj;
261 struct threadlist_entry **entry, *tmp;
263 cleanup = ensure_python_env (python_gdbarch, python_language);
265 inf_obj = (inferior_object *) find_inferior_object (PIDGET(tp->ptid));
268 do_cleanups (cleanup);
272 /* Find thread entry in its inferior's thread_list. */
273 for (entry = &inf_obj->threads; *entry != NULL; entry =
275 if ((*entry)->thread_obj->thread == tp)
281 do_cleanups (cleanup);
286 tmp->thread_obj->thread = NULL;
288 *entry = (*entry)->next;
291 Py_DECREF (tmp->thread_obj);
295 do_cleanups (cleanup);
299 infpy_threads (PyObject *self, PyObject *args)
302 struct threadlist_entry *entry;
303 inferior_object *inf_obj = (inferior_object *) self;
305 volatile struct gdb_exception except;
307 INFPY_REQUIRE_VALID (inf_obj);
309 TRY_CATCH (except, RETURN_MASK_ALL)
310 update_thread_list ();
311 GDB_PY_HANDLE_EXCEPTION (except);
313 tuple = PyTuple_New (inf_obj->nthreads);
317 for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
318 i++, entry = entry->next)
320 Py_INCREF (entry->thread_obj);
321 PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
328 infpy_get_num (PyObject *self, void *closure)
330 inferior_object *inf = (inferior_object *) self;
332 INFPY_REQUIRE_VALID (inf);
334 return PyLong_FromLong (inf->inferior->num);
338 infpy_get_pid (PyObject *self, void *closure)
340 inferior_object *inf = (inferior_object *) self;
342 INFPY_REQUIRE_VALID (inf);
344 return PyLong_FromLong (inf->inferior->pid);
348 infpy_get_was_attached (PyObject *self, void *closure)
350 inferior_object *inf = (inferior_object *) self;
352 INFPY_REQUIRE_VALID (inf);
353 if (inf->inferior->attach_flag)
359 build_inferior_list (struct inferior *inf, void *arg)
361 PyObject *list = arg;
362 PyObject *inferior = inferior_to_inferior_object (inf);
368 success = PyList_Append (list, inferior);
369 Py_DECREF (inferior);
377 /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
378 Returns a tuple of all inferiors. */
380 gdbpy_inferiors (PyObject *unused, PyObject *unused2)
382 PyObject *list, *tuple;
384 list = PyList_New (0);
388 if (iterate_over_inferiors (build_inferior_list, list))
394 tuple = PyList_AsTuple (list);
400 /* Membuf and memory manipulation. */
402 /* Implementation of Inferior.read_memory (address, length).
403 Returns a Python buffer object with LENGTH bytes of the inferior's
404 memory at ADDRESS. Both arguments are integers. Returns NULL on error,
405 with a python exception set. */
407 infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
409 CORE_ADDR addr, length;
411 membuf_object *membuf_obj;
412 PyObject *addr_obj, *length_obj, *result;
413 volatile struct gdb_exception except;
414 static char *keywords[] = { "address", "length", NULL };
416 if (! PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
417 &addr_obj, &length_obj))
420 if (get_addr_from_python (addr_obj, &addr) < 0
421 || get_addr_from_python (length_obj, &length) < 0)
424 TRY_CATCH (except, RETURN_MASK_ALL)
426 buffer = xmalloc (length);
428 read_memory (addr, buffer, length);
430 if (except.reason < 0)
433 GDB_PY_HANDLE_EXCEPTION (except);
436 membuf_obj = PyObject_New (membuf_object, &membuf_object_type);
437 if (membuf_obj == NULL)
443 membuf_obj->buffer = buffer;
444 membuf_obj->addr = addr;
445 membuf_obj->length = length;
448 result = PyMemoryView_FromObject ((PyObject *) membuf_obj);
450 result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
453 Py_DECREF (membuf_obj);
458 /* Implementation of Inferior.write_memory (address, buffer [, length]).
459 Writes the contents of BUFFER (a Python object supporting the read
460 buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
461 bytes from BUFFER, or its entire contents if the argument is not
462 provided. The function returns nothing. Returns NULL on error, with
463 a python exception set. */
465 infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
469 CORE_ADDR addr, length;
470 PyObject *addr_obj, *length_obj = NULL;
471 volatile struct gdb_exception except;
472 static char *keywords[] = { "address", "buffer", "length", NULL };
476 if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
484 if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
485 &addr_obj, &buffer, &buf_len,
490 if (get_addr_from_python (addr_obj, &addr) < 0)
495 else if (get_addr_from_python (length_obj, &length) < 0)
498 TRY_CATCH (except, RETURN_MASK_ALL)
500 write_memory_with_notification (addr, (gdb_byte *) buffer, length);
503 PyBuffer_Release (&pybuf);
505 GDB_PY_HANDLE_EXCEPTION (except);
511 PyBuffer_Release (&pybuf);
516 /* Destructor of Membuf objects. */
518 mbpy_dealloc (PyObject *self)
520 xfree (((membuf_object *) self)->buffer);
521 Py_TYPE (self)->tp_free (self);
524 /* Return a description of the Membuf object. */
526 mbpy_str (PyObject *self)
528 membuf_object *membuf_obj = (membuf_object *) self;
530 return PyString_FromFormat (_("Memory buffer for address %s, \
531 which is %s bytes long."),
532 paddress (python_gdbarch, membuf_obj->addr),
533 pulongest (membuf_obj->length));
539 get_buffer (PyObject *self, Py_buffer *buf, int flags)
541 membuf_object *membuf_obj = (membuf_object *) self;
544 ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer,
545 membuf_obj->length, 0,
555 get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
557 membuf_object *membuf_obj = (membuf_object *) self;
561 PyErr_SetString (PyExc_SystemError,
562 _("The memory buffer supports only one segment."));
566 *ptrptr = membuf_obj->buffer;
568 return membuf_obj->length;
572 get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
574 return get_read_buffer (self, segment, ptrptr);
578 get_seg_count (PyObject *self, Py_ssize_t *lenp)
581 *lenp = ((membuf_object *) self)->length;
587 get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
592 ret = get_read_buffer (self, segment, &ptr);
593 *ptrptr = (char *) ptr;
601 gdb.search_memory (address, length, pattern). ADDRESS is the
602 address to start the search. LENGTH specifies the scope of the
603 search from ADDRESS. PATTERN is the pattern to search for (and
604 must be a Python object supporting the buffer protocol).
605 Returns a Python Long object holding the address where the pattern
606 was located, or if the pattern was not found, returns None. Returns NULL
607 on error, with a python exception set. */
609 infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
611 CORE_ADDR start_addr, length;
612 static char *keywords[] = { "address", "length", "pattern", NULL };
613 PyObject *start_addr_obj, *length_obj;
614 volatile struct gdb_exception except;
615 Py_ssize_t pattern_size;
617 CORE_ADDR found_addr;
622 if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
623 &start_addr_obj, &length_obj,
628 pattern_size = pybuf.len;
632 if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
633 &start_addr_obj, &length_obj,
637 if (!PyObject_CheckReadBuffer (pattern))
639 PyErr_SetString (PyExc_RuntimeError,
640 _("The pattern is not a Python buffer."));
645 if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1)
649 if (get_addr_from_python (start_addr_obj, &start_addr) < 0)
652 if (get_addr_from_python (length_obj, &length) < 0)
657 PyErr_SetString (PyExc_ValueError,
658 _("Search range is empty."));
661 /* Watch for overflows. */
662 else if (length > CORE_ADDR_MAX
663 || (start_addr + length - 1) < start_addr)
665 PyErr_SetString (PyExc_ValueError,
666 _("The search range is too large."));
670 TRY_CATCH (except, RETURN_MASK_ALL)
672 found = target_search_memory (start_addr, length,
673 buffer, pattern_size,
677 PyBuffer_Release (&pybuf);
679 GDB_PY_HANDLE_EXCEPTION (except);
682 return PyLong_FromLong (found_addr);
688 PyBuffer_Release (&pybuf);
693 /* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
694 Returns True if this inferior object still exists in GDB. */
697 infpy_is_valid (PyObject *self, PyObject *args)
699 inferior_object *inf = (inferior_object *) self;
708 infpy_dealloc (PyObject *obj)
710 inferior_object *inf_obj = (inferior_object *) obj;
711 struct inferior *inf = inf_obj->inferior;
716 set_inferior_data (inf, infpy_inf_data_key, NULL);
719 /* Clear the INFERIOR pointer in an Inferior object and clear the
722 py_free_inferior (struct inferior *inf, void *datum)
725 struct cleanup *cleanup;
726 inferior_object *inf_obj = datum;
727 struct threadlist_entry *th_entry, *th_tmp;
729 cleanup = ensure_python_env (python_gdbarch, python_language);
731 inf_obj->inferior = NULL;
733 /* Deallocate threads list. */
734 for (th_entry = inf_obj->threads; th_entry != NULL;)
736 Py_DECREF (th_entry->thread_obj);
739 th_entry = th_entry->next;
743 inf_obj->nthreads = 0;
745 Py_DECREF ((PyObject *) inf_obj);
746 do_cleanups (cleanup);
749 /* Implementation of gdb.selected_inferior() -> gdb.Inferior.
750 Returns the current inferior object. */
753 gdbpy_selected_inferior (PyObject *self, PyObject *args)
757 inf_obj = inferior_to_inferior_object (current_inferior ());
764 gdbpy_initialize_inferior (void)
766 if (PyType_Ready (&inferior_object_type) < 0)
769 Py_INCREF (&inferior_object_type);
770 PyModule_AddObject (gdb_module, "Inferior",
771 (PyObject *) &inferior_object_type);
774 register_inferior_data_with_cleanup (NULL, py_free_inferior);
776 observer_attach_new_thread (add_thread_object);
777 observer_attach_thread_exit (delete_thread_object);
778 observer_attach_normal_stop (python_on_normal_stop);
779 observer_attach_target_resumed (python_on_resume);
780 observer_attach_inferior_exit (python_inferior_exit);
781 observer_attach_new_objfile (python_new_objfile);
783 membuf_object_type.tp_new = PyType_GenericNew;
784 if (PyType_Ready (&membuf_object_type) < 0)
787 Py_INCREF (&membuf_object_type);
788 PyModule_AddObject (gdb_module, "Membuf", (PyObject *)
789 &membuf_object_type);
792 static PyGetSetDef inferior_object_getset[] =
794 { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
795 { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
797 { "was_attached", infpy_get_was_attached, NULL,
798 "True if the inferior was created using 'attach'.", NULL },
802 static PyMethodDef inferior_object_methods[] =
804 { "is_valid", infpy_is_valid, METH_NOARGS,
805 "is_valid () -> Boolean.\n\
806 Return true if this inferior is valid, false if not." },
807 { "threads", infpy_threads, METH_NOARGS,
808 "Return all the threads of this inferior." },
809 { "read_memory", (PyCFunction) infpy_read_memory,
810 METH_VARARGS | METH_KEYWORDS,
811 "read_memory (address, length) -> buffer\n\
812 Return a buffer object for reading from the inferior's memory." },
813 { "write_memory", (PyCFunction) infpy_write_memory,
814 METH_VARARGS | METH_KEYWORDS,
815 "write_memory (address, buffer [, length])\n\
816 Write the given buffer object to the inferior's memory." },
817 { "search_memory", (PyCFunction) infpy_search_memory,
818 METH_VARARGS | METH_KEYWORDS,
819 "search_memory (address, length, pattern) -> long\n\
820 Return a long with the address of a match, or None." },
824 static PyTypeObject inferior_object_type =
826 PyVarObject_HEAD_INIT (NULL, 0)
827 "gdb.Inferior", /* tp_name */
828 sizeof (inferior_object), /* tp_basicsize */
830 infpy_dealloc, /* tp_dealloc */
836 0, /* tp_as_number */
837 0, /* tp_as_sequence */
838 0, /* tp_as_mapping */
844 0, /* tp_as_buffer */
845 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags */
846 "GDB inferior object", /* tp_doc */
849 0, /* tp_richcompare */
850 0, /* tp_weaklistoffset */
853 inferior_object_methods, /* tp_methods */
855 inferior_object_getset, /* tp_getset */
858 0, /* tp_descr_get */
859 0, /* tp_descr_set */
860 0, /* tp_dictoffset */
867 static PyBufferProcs buffer_procs =
874 /* Python doesn't provide a decent way to get compatibility here. */
875 #if HAVE_LIBPYTHON2_4
876 #define CHARBUFFERPROC_NAME getcharbufferproc
878 #define CHARBUFFERPROC_NAME charbufferproc
881 static PyBufferProcs buffer_procs = {
885 /* The cast here works around a difference between Python 2.4 and
887 (CHARBUFFERPROC_NAME) get_char_buffer
891 static PyTypeObject membuf_object_type = {
892 PyVarObject_HEAD_INIT (NULL, 0)
893 "gdb.Membuf", /*tp_name*/
894 sizeof (membuf_object), /*tp_basicsize*/
896 mbpy_dealloc, /*tp_dealloc*/
903 0, /*tp_as_sequence*/
910 &buffer_procs, /*tp_as_buffer*/
911 Py_TPFLAGS_DEFAULT, /*tp_flags*/
912 "GDB memory buffer object", /*tp_doc*/
915 0, /* tp_richcompare */
916 0, /* tp_weaklistoffset */
924 0, /* tp_descr_get */
925 0, /* tp_descr_set */
926 0, /* tp_dictoffset */