1 /* Python interface to inferiors.
3 Copyright (C) 2009, 2010, 2011 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"
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 static PyTypeObject inferior_object_type;
55 static const struct inferior_data *infpy_inf_data_key;
61 /* These are kept just for mbpy_str. */
66 static PyTypeObject membuf_object_type;
68 /* Require that INFERIOR be a valid inferior ID. */
69 #define INFPY_REQUIRE_VALID(Inferior) \
71 if (!Inferior->inferior) \
73 PyErr_SetString (PyExc_RuntimeError, \
74 _("Inferior no longer exists.")); \
80 python_on_normal_stop (struct bpstats *bs, int print_frame)
82 struct cleanup *cleanup;
83 enum target_signal stop_signal;
85 if (!find_thread_ptid (inferior_ptid))
88 stop_signal = inferior_thread ()->suspend.stop_signal;
90 cleanup = ensure_python_env (get_current_arch (), current_language);
92 if (emit_stop_event (bs, stop_signal) < 0)
95 do_cleanups (cleanup);
99 python_on_resume (ptid_t ptid)
101 struct cleanup *cleanup;
103 cleanup = ensure_python_env (target_gdbarch, current_language);
105 if (emit_continue_event (ptid) < 0)
106 gdbpy_print_stack ();
108 do_cleanups (cleanup);
112 python_inferior_exit (struct inferior *inf)
114 struct cleanup *cleanup;
115 const LONGEST *exit_code = NULL;
117 cleanup = ensure_python_env (target_gdbarch, current_language);
119 if (inf->has_exit_code)
120 exit_code = &inf->exit_code;
122 if (emit_exited_event (exit_code) < 0)
123 gdbpy_print_stack ();
125 do_cleanups (cleanup);
128 /* Return a borrowed reference to the Python object of type Inferior
129 representing INFERIOR. If the object has already been created,
130 return it, otherwise, create it. Return NULL on failure. */
132 inferior_to_inferior_object (struct inferior *inferior)
134 inferior_object *inf_obj;
136 inf_obj = inferior_data (inferior, infpy_inf_data_key);
139 struct cleanup *cleanup;
140 cleanup = ensure_python_env (python_gdbarch, python_language);
142 inf_obj = PyObject_New (inferior_object, &inferior_object_type);
145 do_cleanups (cleanup);
149 inf_obj->inferior = inferior;
150 inf_obj->threads = NULL;
151 inf_obj->nthreads = 0;
153 set_inferior_data (inferior, infpy_inf_data_key, inf_obj);
155 do_cleanups (cleanup);
158 return (PyObject *) inf_obj;
161 /* Finds the Python Inferior object for the given PID. Returns a
162 borrowed reference, or NULL if PID does not match any inferior
166 find_inferior_object (int pid)
168 struct inflist_entry *p;
169 struct inferior *inf = find_inferior_pid (pid);
172 return inferior_to_inferior_object (inf);
178 find_thread_object (ptid_t ptid)
181 struct threadlist_entry *thread;
188 inf_obj = find_inferior_object (pid);
191 for (thread = ((inferior_object *)inf_obj)->threads; thread;
192 thread = thread->next)
193 if (ptid_equal (thread->thread_obj->thread->ptid, ptid))
194 return thread->thread_obj;
200 add_thread_object (struct thread_info *tp)
202 struct cleanup *cleanup;
203 thread_object *thread_obj;
204 inferior_object *inf_obj;
205 struct threadlist_entry *entry;
207 cleanup = ensure_python_env (python_gdbarch, python_language);
209 thread_obj = create_thread_object (tp);
212 gdbpy_print_stack ();
213 do_cleanups (cleanup);
217 inf_obj = (inferior_object *) thread_obj->inf_obj;
219 entry = xmalloc (sizeof (struct threadlist_entry));
220 entry->thread_obj = thread_obj;
221 entry->next = inf_obj->threads;
223 inf_obj->threads = entry;
226 do_cleanups (cleanup);
230 delete_thread_object (struct thread_info *tp, int ignore)
232 struct cleanup *cleanup;
233 inferior_object *inf_obj;
234 thread_object *thread_obj;
235 struct threadlist_entry **entry, *tmp;
237 inf_obj = (inferior_object *) find_inferior_object (PIDGET(tp->ptid));
241 /* Find thread entry in its inferior's thread_list. */
242 for (entry = &inf_obj->threads; *entry != NULL; entry =
244 if ((*entry)->thread_obj->thread == tp)
250 cleanup = ensure_python_env (python_gdbarch, python_language);
253 tmp->thread_obj->thread = NULL;
255 *entry = (*entry)->next;
258 Py_DECREF (tmp->thread_obj);
261 do_cleanups (cleanup);
265 infpy_threads (PyObject *self, PyObject *args)
268 struct threadlist_entry *entry;
269 inferior_object *inf_obj = (inferior_object *) self;
272 INFPY_REQUIRE_VALID (inf_obj);
274 tuple = PyTuple_New (inf_obj->nthreads);
278 for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
279 i++, entry = entry->next)
281 Py_INCREF (entry->thread_obj);
282 PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
289 infpy_get_num (PyObject *self, void *closure)
291 inferior_object *inf = (inferior_object *) self;
293 INFPY_REQUIRE_VALID (inf);
295 return PyLong_FromLong (inf->inferior->num);
299 infpy_get_pid (PyObject *self, void *closure)
301 inferior_object *inf = (inferior_object *) self;
303 INFPY_REQUIRE_VALID (inf);
305 return PyLong_FromLong (inf->inferior->pid);
309 infpy_get_was_attached (PyObject *self, void *closure)
311 inferior_object *inf = (inferior_object *) self;
313 INFPY_REQUIRE_VALID (inf);
314 if (inf->inferior->attach_flag)
320 build_inferior_list (struct inferior *inf, void *arg)
322 PyObject *list = arg;
323 PyObject *inferior = inferior_to_inferior_object (inf);
325 if (PyList_Append (list, inferior))
331 /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
332 Returns a tuple of all inferiors. */
334 gdbpy_inferiors (PyObject *unused, PyObject *unused2)
337 PyObject *list, *inferior;
338 struct inferior *inf;
340 list = PyList_New (0);
344 if (iterate_over_inferiors (build_inferior_list, list))
350 return PyList_AsTuple (list);
353 /* Membuf and memory manipulation. */
355 /* Implementation of gdb.read_memory (address, length).
356 Returns a Python buffer object with LENGTH bytes of the inferior's
357 memory at ADDRESS. Both arguments are integers. Returns NULL on error,
358 with a python exception set. */
360 infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
363 CORE_ADDR addr, length;
365 membuf_object *membuf_obj;
366 PyObject *addr_obj, *length_obj;
367 struct cleanup *cleanups;
368 volatile struct gdb_exception except;
369 static char *keywords[] = { "address", "length", NULL };
371 if (! PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
372 &addr_obj, &length_obj))
375 cleanups = make_cleanup (null_cleanup, NULL);
377 TRY_CATCH (except, RETURN_MASK_ALL)
379 if (!get_addr_from_python (addr_obj, &addr)
380 || !get_addr_from_python (length_obj, &length))
386 buffer = xmalloc (length);
387 make_cleanup (xfree, buffer);
389 read_memory (addr, buffer, length);
391 if (except.reason < 0)
393 do_cleanups (cleanups);
394 GDB_PY_HANDLE_EXCEPTION (except);
399 do_cleanups (cleanups);
403 membuf_obj = PyObject_New (membuf_object, &membuf_object_type);
404 if (membuf_obj == NULL)
406 PyErr_SetString (PyExc_MemoryError,
407 _("Could not allocate memory buffer object."));
408 do_cleanups (cleanups);
412 discard_cleanups (cleanups);
414 membuf_obj->buffer = buffer;
415 membuf_obj->addr = addr;
416 membuf_obj->length = length;
418 return PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
422 /* Implementation of gdb.write_memory (address, buffer [, length]).
423 Writes the contents of BUFFER (a Python object supporting the read
424 buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
425 bytes from BUFFER, or its entire contents if the argument is not
426 provided. The function returns nothing. Returns NULL on error, with
427 a python exception set. */
429 infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
431 int buf_len, error = 0;
433 CORE_ADDR addr, length;
434 PyObject *addr_obj, *length_obj = NULL;
435 volatile struct gdb_exception except;
436 static char *keywords[] = { "address", "buffer", "length", NULL };
439 if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
440 &addr_obj, &buffer, &buf_len,
444 TRY_CATCH (except, RETURN_MASK_ALL)
446 if (!get_addr_from_python (addr_obj, &addr))
454 else if (!get_addr_from_python (length_obj, &length))
459 write_memory (addr, buffer, length);
461 GDB_PY_HANDLE_EXCEPTION (except);
469 /* Destructor of Membuf objects. */
471 mbpy_dealloc (PyObject *self)
473 xfree (((membuf_object *) self)->buffer);
474 self->ob_type->tp_free (self);
477 /* Return a description of the Membuf object. */
479 mbpy_str (PyObject *self)
481 membuf_object *membuf_obj = (membuf_object *) self;
483 return PyString_FromFormat (_("Memory buffer for address %s, \
484 which is %s bytes long."),
485 paddress (python_gdbarch, membuf_obj->addr),
486 pulongest (membuf_obj->length));
490 get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
492 membuf_object *membuf_obj = (membuf_object *) self;
496 PyErr_SetString (PyExc_SystemError,
497 _("The memory buffer supports only one segment."));
501 *ptrptr = membuf_obj->buffer;
503 return membuf_obj->length;
507 get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
509 return get_read_buffer (self, segment, ptrptr);
513 get_seg_count (PyObject *self, Py_ssize_t *lenp)
516 *lenp = ((membuf_object *) self)->length;
522 get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
527 ret = get_read_buffer (self, segment, &ptr);
528 *ptrptr = (char *) ptr;
534 gdb.search_memory (address, length, pattern). ADDRESS is the
535 address to start the search. LENGTH specifies the scope of the
536 search from ADDRESS. PATTERN is the pattern to search for (and
537 must be a Python object supporting the buffer protocol).
538 Returns a Python Long object holding the address where the pattern
539 was located, or if the pattern was not found, returns None. Returns NULL
540 on error, with a python exception set. */
542 infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
544 CORE_ADDR start_addr, length;
545 static char *keywords[] = { "address", "length", "pattern", NULL };
546 PyObject *pattern, *start_addr_obj, *length_obj;
547 volatile struct gdb_exception except;
548 Py_ssize_t pattern_size;
550 CORE_ADDR found_addr;
553 if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
554 &start_addr_obj, &length_obj,
558 if (get_addr_from_python (start_addr_obj, &start_addr)
559 && get_addr_from_python (length_obj, &length))
563 PyErr_SetString (PyExc_ValueError,
564 _("Search range is empty."));
567 /* Watch for overflows. */
568 else if (length > CORE_ADDR_MAX
569 || (start_addr + length - 1) < start_addr)
571 PyErr_SetString (PyExc_ValueError,
572 _("The search range is too large."));
580 if (!PyObject_CheckReadBuffer (pattern))
582 PyErr_SetString (PyExc_RuntimeError,
583 _("The pattern is not a Python buffer."));
588 if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1)
591 TRY_CATCH (except, RETURN_MASK_ALL)
593 found = target_search_memory (start_addr, length,
594 buffer, pattern_size,
597 GDB_PY_HANDLE_EXCEPTION (except);
600 return PyLong_FromLong (found_addr);
605 /* Implementation of gdb.Inferior.is_valid (self) -> Boolean.
606 Returns True if this inferior object still exists in GDB. */
609 infpy_is_valid (PyObject *self, PyObject *args)
611 inferior_object *inf = (inferior_object *) self;
620 /* Clear the INFERIOR pointer in an Inferior object and clear the
623 py_free_inferior (struct inferior *inf, void *datum)
626 struct cleanup *cleanup;
627 inferior_object *inf_obj = datum;
628 struct threadlist_entry *th_entry, *th_tmp;
630 cleanup = ensure_python_env (python_gdbarch, python_language);
632 inf_obj->inferior = NULL;
634 /* Deallocate threads list. */
635 for (th_entry = inf_obj->threads; th_entry != NULL;)
637 Py_DECREF (th_entry->thread_obj);
640 th_entry = th_entry->next;
644 inf_obj->nthreads = 0;
646 Py_DECREF ((PyObject *) inf_obj);
647 do_cleanups (cleanup);
651 gdbpy_initialize_inferior (void)
653 if (PyType_Ready (&inferior_object_type) < 0)
656 Py_INCREF (&inferior_object_type);
657 PyModule_AddObject (gdb_module, "Inferior",
658 (PyObject *) &inferior_object_type);
661 register_inferior_data_with_cleanup (py_free_inferior);
663 observer_attach_new_thread (add_thread_object);
664 observer_attach_thread_exit (delete_thread_object);
665 observer_attach_normal_stop (python_on_normal_stop);
666 observer_attach_target_resumed (python_on_resume);
667 observer_attach_inferior_exit (python_inferior_exit);
669 if (PyType_Ready (&membuf_object_type) < 0)
672 Py_INCREF (&membuf_object_type);
673 PyModule_AddObject (gdb_module, "Membuf", (PyObject *)
674 &membuf_object_type);
677 static PyGetSetDef inferior_object_getset[] =
679 { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
680 { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
682 { "was_attached", infpy_get_was_attached, NULL,
683 "True if the inferior was created using 'attach'.", NULL },
687 static PyMethodDef inferior_object_methods[] =
689 { "is_valid", infpy_is_valid, METH_NOARGS,
690 "is_valid () -> Boolean.\n\
691 Return true if this inferior is valid, false if not." },
692 { "threads", infpy_threads, METH_NOARGS,
693 "Return all the threads of this inferior." },
694 { "read_memory", (PyCFunction) infpy_read_memory,
695 METH_VARARGS | METH_KEYWORDS,
696 "read_memory (address, length) -> buffer\n\
697 Return a buffer object for reading from the inferior's memory." },
698 { "write_memory", (PyCFunction) infpy_write_memory,
699 METH_VARARGS | METH_KEYWORDS,
700 "write_memory (address, buffer [, length])\n\
701 Write the given buffer object to the inferior's memory." },
702 { "search_memory", (PyCFunction) infpy_search_memory,
703 METH_VARARGS | METH_KEYWORDS,
704 "search_memory (address, length, pattern) -> long\n\
705 Return a long with the address of a match, or None." },
709 static PyTypeObject inferior_object_type =
711 PyObject_HEAD_INIT (NULL)
713 "gdb.Inferior", /* tp_name */
714 sizeof (inferior_object), /* tp_basicsize */
722 0, /* tp_as_number */
723 0, /* tp_as_sequence */
724 0, /* tp_as_mapping */
730 0, /* tp_as_buffer */
731 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags */
732 "GDB inferior object", /* tp_doc */
735 0, /* tp_richcompare */
736 0, /* tp_weaklistoffset */
739 inferior_object_methods, /* tp_methods */
741 inferior_object_getset, /* tp_getset */
744 0, /* tp_descr_get */
745 0, /* tp_descr_set */
746 0, /* tp_dictoffset */
751 /* Python doesn't provide a decent way to get compatibility here. */
752 #if HAVE_LIBPYTHON2_4
753 #define CHARBUFFERPROC_NAME getcharbufferproc
755 #define CHARBUFFERPROC_NAME charbufferproc
758 static PyBufferProcs buffer_procs = {
762 /* The cast here works around a difference between Python 2.4 and
764 (CHARBUFFERPROC_NAME) get_char_buffer
767 static PyTypeObject membuf_object_type = {
768 PyObject_HEAD_INIT (NULL)
770 "gdb.Membuf", /*tp_name*/
771 sizeof (membuf_object), /*tp_basicsize*/
773 mbpy_dealloc, /*tp_dealloc*/
780 0, /*tp_as_sequence*/
787 &buffer_procs, /*tp_as_buffer*/
788 Py_TPFLAGS_DEFAULT, /*tp_flags*/
789 "GDB memory buffer object", /*tp_doc*/
792 0, /* tp_richcompare */
793 0, /* tp_weaklistoffset */
801 0, /* tp_descr_get */
802 0, /* tp_descr_set */
803 0, /* tp_dictoffset */
806 PyType_GenericNew /* tp_new */