gdb/
[deliverable/binutils-gdb.git] / gdb / python / py-inferior.c
1 /* Python interface to inferiors.
2
3 Copyright (C) 2009, 2010 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 "exceptions.h"
22 #include "gdbcore.h"
23 #include "gdbthread.h"
24 #include "inferior.h"
25 #include "observer.h"
26 #include "python-internal.h"
27 #include "arch-utils.h"
28 #include "language.h"
29
30 struct threadlist_entry {
31 thread_object *thread_obj;
32 struct threadlist_entry *next;
33 };
34
35 typedef struct
36 {
37 PyObject_HEAD
38
39 /* The inferior we represent. */
40 struct inferior *inferior;
41
42 /* thread_object instances under this inferior. This list owns a
43 reference to each object it contains. */
44 struct threadlist_entry *threads;
45
46 /* Number of threads in the list. */
47 int nthreads;
48 } inferior_object;
49
50 static PyTypeObject inferior_object_type;
51
52 static const struct inferior_data *infpy_inf_data_key;
53
54 typedef struct {
55 PyObject_HEAD
56 void *buffer;
57
58 /* These are kept just for mbpy_str. */
59 CORE_ADDR addr;
60 CORE_ADDR length;
61 } membuf_object;
62
63 static PyTypeObject membuf_object_type;
64
65 /* Require that INFERIOR be a valid inferior ID. */
66 #define INFPY_REQUIRE_VALID(Inferior) \
67 do { \
68 if (!Inferior->inferior) \
69 { \
70 PyErr_SetString (PyExc_RuntimeError, \
71 _("Inferior no longer exists.")); \
72 return NULL; \
73 } \
74 } while (0)
75
76 /* Return a borrowed reference to the Python object of type Inferior
77 representing INFERIOR. If the object has already been created,
78 return it, otherwise, create it. Return NULL on failure. */
79 PyObject *
80 inferior_to_inferior_object (struct inferior *inferior)
81 {
82 inferior_object *inf_obj;
83
84 inf_obj = inferior_data (inferior, infpy_inf_data_key);
85 if (!inf_obj)
86 {
87 struct cleanup *cleanup;
88 cleanup = ensure_python_env (python_gdbarch, python_language);
89
90 inf_obj = PyObject_New (inferior_object, &inferior_object_type);
91 if (!inf_obj)
92 {
93 do_cleanups (cleanup);
94 return NULL;
95 }
96
97 inf_obj->inferior = inferior;
98 inf_obj->threads = NULL;
99 inf_obj->nthreads = 0;
100
101 set_inferior_data (inferior, infpy_inf_data_key, inf_obj);
102
103 do_cleanups (cleanup);
104 }
105
106 return (PyObject *) inf_obj;
107 }
108
109 /* Finds the Python Inferior object for the given PID. Returns a
110 borrowed reference, or NULL if PID does not match any inferior
111 obect.
112 */
113 PyObject *
114 find_inferior_object (int pid)
115 {
116 struct inflist_entry *p;
117 struct inferior *inf = find_inferior_pid (pid);
118
119 if (inf)
120 return inferior_to_inferior_object (inf);
121
122 return NULL;
123 }
124
125 thread_object *
126 find_thread_object (ptid_t ptid)
127 {
128 int pid;
129 struct threadlist_entry *thread;
130 PyObject *inf_obj;
131
132 pid = PIDGET (ptid);
133 inf_obj = find_inferior_object (pid);
134
135 if (inf_obj)
136 for (thread = ((inferior_object *)inf_obj)->threads; thread;
137 thread = thread->next)
138 if (ptid_equal (thread->thread_obj->thread->ptid, ptid))
139 return thread->thread_obj;
140
141 return NULL;
142 }
143
144 static void
145 add_thread_object (struct thread_info *tp)
146 {
147 struct cleanup *cleanup;
148 thread_object *thread_obj;
149 inferior_object *inf_obj;
150 struct threadlist_entry *entry;
151
152 cleanup = ensure_python_env (python_gdbarch, python_language);
153
154 thread_obj = create_thread_object (tp);
155 if (!thread_obj)
156 {
157 gdbpy_print_stack ();
158 do_cleanups (cleanup);
159 return;
160 }
161
162 inf_obj = (inferior_object *) thread_obj->inf_obj;
163
164 entry = xmalloc (sizeof (struct threadlist_entry));
165 entry->thread_obj = thread_obj;
166 entry->next = inf_obj->threads;
167
168 inf_obj->threads = entry;
169 inf_obj->nthreads++;
170
171 do_cleanups (cleanup);
172 }
173
174 static void
175 delete_thread_object (struct thread_info *tp, int ignore)
176 {
177 struct cleanup *cleanup;
178 inferior_object *inf_obj;
179 thread_object *thread_obj;
180 struct threadlist_entry **entry, *tmp;
181
182 inf_obj = (inferior_object *) find_inferior_object (PIDGET(tp->ptid));
183 if (!inf_obj)
184 return;
185
186 /* Find thread entry in its inferior's thread_list. */
187 for (entry = &inf_obj->threads; *entry != NULL; entry =
188 &(*entry)->next)
189 if ((*entry)->thread_obj->thread == tp)
190 break;
191
192 if (!*entry)
193 return;
194
195 cleanup = ensure_python_env (python_gdbarch, python_language);
196
197 tmp = *entry;
198 tmp->thread_obj->thread = NULL;
199
200 *entry = (*entry)->next;
201 inf_obj->nthreads--;
202
203 Py_DECREF (tmp->thread_obj);
204 xfree (tmp);
205
206 do_cleanups (cleanup);
207 }
208
209 static PyObject *
210 infpy_threads (PyObject *self, PyObject *args)
211 {
212 int i;
213 struct threadlist_entry *entry;
214 inferior_object *inf_obj = (inferior_object *) self;
215 PyObject *tuple;
216
217 INFPY_REQUIRE_VALID (inf_obj);
218
219 tuple = PyTuple_New (inf_obj->nthreads);
220 if (!tuple)
221 return NULL;
222
223 for (i = 0, entry = inf_obj->threads; i < inf_obj->nthreads;
224 i++, entry = entry->next)
225 {
226 Py_INCREF (entry->thread_obj);
227 PyTuple_SET_ITEM (tuple, i, (PyObject *) entry->thread_obj);
228 }
229
230 return tuple;
231 }
232
233 static PyObject *
234 infpy_get_num (PyObject *self, void *closure)
235 {
236 inferior_object *inf = (inferior_object *) self;
237
238 INFPY_REQUIRE_VALID (inf);
239
240 return PyLong_FromLong (inf->inferior->num);
241 }
242
243 static PyObject *
244 infpy_get_pid (PyObject *self, void *closure)
245 {
246 inferior_object *inf = (inferior_object *) self;
247
248 INFPY_REQUIRE_VALID (inf);
249
250 return PyLong_FromLong (inf->inferior->pid);
251 }
252
253 static PyObject *
254 infpy_get_was_attached (PyObject *self, void *closure)
255 {
256 inferior_object *inf = (inferior_object *) self;
257
258 INFPY_REQUIRE_VALID (inf);
259 if (inf->inferior->attach_flag)
260 Py_RETURN_TRUE;
261 Py_RETURN_FALSE;
262 }
263
264 static int
265 build_inferior_list (struct inferior *inf, void *arg)
266 {
267 PyObject *list = arg;
268 PyObject *inferior = inferior_to_inferior_object (inf);
269
270 PyList_Append (list, inferior);
271 return 0;
272 }
273
274 /* Implementation of gdb.inferiors () -> (gdb.Inferior, ...).
275 Returns a tuple of all inferiors. */
276 PyObject *
277 gdbpy_inferiors (PyObject *unused, PyObject *unused2)
278 {
279 int i = 0;
280 PyObject *list, *inferior;
281 struct inferior *inf;
282
283 list = PyList_New (0);
284 if (!list)
285 return NULL;
286
287 iterate_over_inferiors (build_inferior_list, list);
288
289 return PyList_AsTuple (list);
290 }
291
292 /* Membuf and memory manipulation. */
293
294 /* Implementation of gdb.read_memory (address, length).
295 Returns a Python buffer object with LENGTH bytes of the inferior's
296 memory at ADDRESS. Both arguments are integers. Returns NULL on error,
297 with a python exception set. */
298 static PyObject *
299 infpy_read_memory (PyObject *self, PyObject *args, PyObject *kw)
300 {
301 int error = 0;
302 CORE_ADDR addr, length;
303 void *buffer = NULL;
304 membuf_object *membuf_obj;
305 PyObject *addr_obj, *length_obj;
306 struct cleanup *cleanups;
307 volatile struct gdb_exception except;
308 static char *keywords[] = { "address", "length", NULL };
309
310 if (! PyArg_ParseTupleAndKeywords (args, kw, "OO", keywords,
311 &addr_obj, &length_obj))
312 return NULL;
313
314 cleanups = make_cleanup (null_cleanup, NULL);
315
316 TRY_CATCH (except, RETURN_MASK_ALL)
317 {
318 if (!get_addr_from_python (addr_obj, &addr)
319 || !get_addr_from_python (length_obj, &length))
320 {
321 error = 1;
322 break;
323 }
324
325 buffer = xmalloc (length);
326 make_cleanup (xfree, buffer);
327
328 read_memory (addr, buffer, length);
329 }
330 if (except.reason < 0)
331 {
332 do_cleanups (cleanups);
333 GDB_PY_HANDLE_EXCEPTION (except);
334 }
335
336 if (error)
337 {
338 do_cleanups (cleanups);
339 return NULL;
340 }
341
342 membuf_obj = PyObject_New (membuf_object, &membuf_object_type);
343 if (membuf_obj == NULL)
344 {
345 PyErr_SetString (PyExc_MemoryError,
346 _("Could not allocate memory buffer object."));
347 do_cleanups (cleanups);
348 return NULL;
349 }
350
351 discard_cleanups (cleanups);
352
353 membuf_obj->buffer = buffer;
354 membuf_obj->addr = addr;
355 membuf_obj->length = length;
356
357 return PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
358 Py_END_OF_BUFFER);
359 }
360
361 /* Implementation of gdb.write_memory (address, buffer [, length]).
362 Writes the contents of BUFFER (a Python object supporting the read
363 buffer protocol) at ADDRESS in the inferior's memory. Write LENGTH
364 bytes from BUFFER, or its entire contents if the argument is not
365 provided. The function returns nothing. Returns NULL on error, with
366 a python exception set. */
367 static PyObject *
368 infpy_write_memory (PyObject *self, PyObject *args, PyObject *kw)
369 {
370 int buf_len, error = 0;
371 const char *buffer;
372 CORE_ADDR addr, length;
373 PyObject *addr_obj, *length_obj = NULL;
374 volatile struct gdb_exception except;
375 static char *keywords[] = { "address", "buffer", "length", NULL };
376
377
378 if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
379 &addr_obj, &buffer, &buf_len,
380 &length_obj))
381 return NULL;
382
383 TRY_CATCH (except, RETURN_MASK_ALL)
384 {
385 if (!get_addr_from_python (addr_obj, &addr))
386 {
387 error = 1;
388 break;
389 }
390
391 if (!length_obj)
392 length = buf_len;
393 else if (!get_addr_from_python (length_obj, &length))
394 {
395 error = 1;
396 break;
397 }
398 write_memory (addr, buffer, length);
399 }
400 GDB_PY_HANDLE_EXCEPTION (except);
401
402 if (error)
403 return NULL;
404
405 Py_RETURN_NONE;
406 }
407
408 /* Destructor of Membuf objects. */
409 static void
410 mbpy_dealloc (PyObject *self)
411 {
412 xfree (((membuf_object *) self)->buffer);
413 self->ob_type->tp_free (self);
414 }
415
416 /* Return a description of the Membuf object. */
417 static PyObject *
418 mbpy_str (PyObject *self)
419 {
420 membuf_object *membuf_obj = (membuf_object *) self;
421
422 return PyString_FromFormat (_("Memory buffer for address %s, \
423 which is %s bytes long."),
424 paddress (python_gdbarch, membuf_obj->addr),
425 pulongest (membuf_obj->length));
426 }
427
428 static Py_ssize_t
429 get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
430 {
431 membuf_object *membuf_obj = (membuf_object *) self;
432
433 if (segment)
434 {
435 PyErr_SetString (PyExc_SystemError,
436 _("The memory buffer supports only one segment."));
437 return -1;
438 }
439
440 *ptrptr = membuf_obj->buffer;
441
442 return membuf_obj->length;
443 }
444
445 static Py_ssize_t
446 get_write_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
447 {
448 return get_read_buffer (self, segment, ptrptr);
449 }
450
451 static Py_ssize_t
452 get_seg_count (PyObject *self, Py_ssize_t *lenp)
453 {
454 if (lenp)
455 *lenp = ((membuf_object *) self)->length;
456
457 return 1;
458 }
459
460 static Py_ssize_t
461 get_char_buffer (PyObject *self, Py_ssize_t segment, char **ptrptr)
462 {
463 void *ptr = NULL;
464 Py_ssize_t ret;
465
466 ret = get_read_buffer (self, segment, &ptr);
467 *ptrptr = (char *) ptr;
468
469 return ret;
470 }
471
472 /* Implementation of
473 gdb.search_memory (address, length, pattern). ADDRESS is the
474 address to start the search. LENGTH specifies the scope of the
475 search from ADDRESS. PATTERN is the pattern to search for (and
476 must be a Python object supporting the buffer protocol).
477 Returns a Python Long object holding the address where the pattern
478 was located, or if the pattern was not found, returns None. Returns NULL
479 on error, with a python exception set. */
480 static PyObject *
481 infpy_search_memory (PyObject *self, PyObject *args, PyObject *kw)
482 {
483 CORE_ADDR start_addr, length;
484 static char *keywords[] = { "address", "length", "pattern", NULL };
485 PyObject *pattern, *start_addr_obj, *length_obj;
486 volatile struct gdb_exception except;
487 Py_ssize_t pattern_size;
488 const void *buffer;
489 CORE_ADDR found_addr;
490 int found = 0;
491
492 if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
493 &start_addr_obj, &length_obj,
494 &pattern))
495 return NULL;
496
497 if (get_addr_from_python (start_addr_obj, &start_addr)
498 && get_addr_from_python (length_obj, &length))
499 {
500 if (!length)
501 {
502 PyErr_SetString (PyExc_ValueError,
503 _("Search range is empty."));
504 return NULL;
505 }
506 /* Watch for overflows. */
507 else if (length > CORE_ADDR_MAX
508 || (start_addr + length - 1) < start_addr)
509 {
510 PyErr_SetString (PyExc_ValueError,
511 _("The search range is too large."));
512
513 return NULL;
514 }
515 }
516 else
517 return NULL;
518
519 if (!PyObject_CheckReadBuffer (pattern))
520 {
521 PyErr_SetString (PyExc_RuntimeError,
522 _("The pattern is not a Python buffer."));
523
524 return NULL;
525 }
526
527 if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1)
528 return NULL;
529
530 TRY_CATCH (except, RETURN_MASK_ALL)
531 {
532 found = target_search_memory (start_addr, length,
533 buffer, pattern_size,
534 &found_addr);
535 }
536 GDB_PY_HANDLE_EXCEPTION (except);
537
538 if (found)
539 return PyLong_FromLong (found_addr);
540 else
541 Py_RETURN_NONE;
542 }
543
544
545 /* Clear the INFERIOR pointer in an Inferior object and clear the
546 thread list. */
547 static void
548 py_free_inferior (struct inferior *inf, void *datum)
549 {
550
551 struct cleanup *cleanup;
552 inferior_object *inf_obj = datum;
553 struct threadlist_entry *th_entry, *th_tmp;
554
555 cleanup = ensure_python_env (python_gdbarch, python_language);
556
557 inf_obj->inferior = NULL;
558
559 /* Deallocate threads list. */
560 for (th_entry = inf_obj->threads; th_entry != NULL;)
561 {
562 Py_DECREF (th_entry->thread_obj);
563
564 th_tmp = th_entry;
565 th_entry = th_entry->next;
566 xfree (th_tmp);
567 }
568
569 inf_obj->nthreads = 0;
570
571 Py_DECREF ((PyObject *) inf_obj);
572 do_cleanups (cleanup);
573 }
574
575 void
576 gdbpy_initialize_inferior (void)
577 {
578 if (PyType_Ready (&inferior_object_type) < 0)
579 return;
580
581 Py_INCREF (&inferior_object_type);
582 PyModule_AddObject (gdb_module, "Inferior",
583 (PyObject *) &inferior_object_type);
584
585 infpy_inf_data_key =
586 register_inferior_data_with_cleanup (py_free_inferior);
587
588 observer_attach_new_thread (add_thread_object);
589 observer_attach_thread_exit (delete_thread_object);
590
591 if (PyType_Ready (&membuf_object_type) < 0)
592 return;
593
594 Py_INCREF (&membuf_object_type);
595 PyModule_AddObject (gdb_module, "Membuf", (PyObject *)
596 &membuf_object_type);
597 }
598
599 static PyGetSetDef inferior_object_getset[] =
600 {
601 { "num", infpy_get_num, NULL, "ID of inferior, as assigned by GDB.", NULL },
602 { "pid", infpy_get_pid, NULL, "PID of inferior, as assigned by the OS.",
603 NULL },
604 { "was_attached", infpy_get_was_attached, NULL,
605 "True if the inferior was created using 'attach'.", NULL },
606 { NULL }
607 };
608
609 static PyMethodDef inferior_object_methods[] =
610 {
611 { "threads", infpy_threads, METH_NOARGS,
612 "Return all the threads of this inferior." },
613 { "read_memory", (PyCFunction) infpy_read_memory,
614 METH_VARARGS | METH_KEYWORDS,
615 "read_memory (address, length) -> buffer\n\
616 Return a buffer object for reading from the inferior's memory." },
617 { "write_memory", (PyCFunction) infpy_write_memory,
618 METH_VARARGS | METH_KEYWORDS,
619 "write_memory (address, buffer [, length])\n\
620 Write the given buffer object to the inferior's memory." },
621 { "search_memory", (PyCFunction) infpy_search_memory,
622 METH_VARARGS | METH_KEYWORDS,
623 "search_memory (address, length, pattern) -> long\n\
624 Return a long with the address of a match, or None." },
625 { NULL }
626 };
627
628 static PyTypeObject inferior_object_type =
629 {
630 PyObject_HEAD_INIT (NULL)
631 0, /* ob_size */
632 "gdb.Inferior", /* tp_name */
633 sizeof (inferior_object), /* tp_basicsize */
634 0, /* tp_itemsize */
635 0, /* tp_dealloc */
636 0, /* tp_print */
637 0, /* tp_getattr */
638 0, /* tp_setattr */
639 0, /* tp_compare */
640 0, /* tp_repr */
641 0, /* tp_as_number */
642 0, /* tp_as_sequence */
643 0, /* tp_as_mapping */
644 0, /* tp_hash */
645 0, /* tp_call */
646 0, /* tp_str */
647 0, /* tp_getattro */
648 0, /* tp_setattro */
649 0, /* tp_as_buffer */
650 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_ITER, /* tp_flags */
651 "GDB inferior object", /* tp_doc */
652 0, /* tp_traverse */
653 0, /* tp_clear */
654 0, /* tp_richcompare */
655 0, /* tp_weaklistoffset */
656 0, /* tp_iter */
657 0, /* tp_iternext */
658 inferior_object_methods, /* tp_methods */
659 0, /* tp_members */
660 inferior_object_getset, /* tp_getset */
661 0, /* tp_base */
662 0, /* tp_dict */
663 0, /* tp_descr_get */
664 0, /* tp_descr_set */
665 0, /* tp_dictoffset */
666 0, /* tp_init */
667 0 /* tp_alloc */
668 };
669
670 /* Python doesn't provide a decent way to get compatibility here. */
671 #if HAVE_LIBPYTHON2_4
672 #define CHARBUFFERPROC_NAME getcharbufferproc
673 #else
674 #define CHARBUFFERPROC_NAME charbufferproc
675 #endif
676
677 static PyBufferProcs buffer_procs = {
678 get_read_buffer,
679 get_write_buffer,
680 get_seg_count,
681 /* The cast here works around a difference between Python 2.4 and
682 Python 2.5. */
683 (CHARBUFFERPROC_NAME) get_char_buffer
684 };
685
686 static PyTypeObject membuf_object_type = {
687 PyObject_HEAD_INIT (NULL)
688 0, /*ob_size*/
689 "gdb.Membuf", /*tp_name*/
690 sizeof (membuf_object), /*tp_basicsize*/
691 0, /*tp_itemsize*/
692 mbpy_dealloc, /*tp_dealloc*/
693 0, /*tp_print*/
694 0, /*tp_getattr*/
695 0, /*tp_setattr*/
696 0, /*tp_compare*/
697 0, /*tp_repr*/
698 0, /*tp_as_number*/
699 0, /*tp_as_sequence*/
700 0, /*tp_as_mapping*/
701 0, /*tp_hash */
702 0, /*tp_call*/
703 mbpy_str, /*tp_str*/
704 0, /*tp_getattro*/
705 0, /*tp_setattro*/
706 &buffer_procs, /*tp_as_buffer*/
707 Py_TPFLAGS_DEFAULT, /*tp_flags*/
708 "GDB memory buffer object", /*tp_doc*/
709 0, /* tp_traverse */
710 0, /* tp_clear */
711 0, /* tp_richcompare */
712 0, /* tp_weaklistoffset */
713 0, /* tp_iter */
714 0, /* tp_iternext */
715 0, /* tp_methods */
716 0, /* tp_members */
717 0, /* tp_getset */
718 0, /* tp_base */
719 0, /* tp_dict */
720 0, /* tp_descr_get */
721 0, /* tp_descr_set */
722 0, /* tp_dictoffset */
723 0, /* tp_init */
724 0, /* tp_alloc */
725 PyType_GenericNew /* tp_new */
726 };
This page took 0.047796 seconds and 5 git commands to generate.