]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/python/python.c
2011-07-11 Phil Muldoon <pmuldoon@redhat.com>
[thirdparty/binutils-gdb.git] / gdb / python / python.c
1 /* General python/gdb code
2
3 Copyright (C) 2008, 2009, 2010, 2011 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 "arch-utils.h"
22 #include "command.h"
23 #include "ui-out.h"
24 #include "cli/cli-script.h"
25 #include "gdbcmd.h"
26 #include "progspace.h"
27 #include "objfiles.h"
28 #include "value.h"
29 #include "language.h"
30 #include "exceptions.h"
31 #include "event-loop.h"
32 #include "serial.h"
33 #include "python.h"
34
35 #include <ctype.h>
36
37 /* True if we should print the stack when catching a Python error,
38 false otherwise. */
39 static int gdbpy_should_print_stack = 0;
40
41 #ifdef HAVE_PYTHON
42
43 #include "libiberty.h"
44 #include "cli/cli-decode.h"
45 #include "charset.h"
46 #include "top.h"
47 #include "solib.h"
48 #include "python-internal.h"
49 #include "linespec.h"
50 #include "source.h"
51 #include "version.h"
52 #include "target.h"
53 #include "gdbthread.h"
54
55 static PyMethodDef GdbMethods[];
56
57 PyObject *gdb_module;
58
59 /* Some string constants we may wish to use. */
60 PyObject *gdbpy_to_string_cst;
61 PyObject *gdbpy_children_cst;
62 PyObject *gdbpy_display_hint_cst;
63 PyObject *gdbpy_doc_cst;
64 PyObject *gdbpy_enabled_cst;
65 PyObject *gdbpy_value_cst;
66
67 /* The GdbError exception. */
68 PyObject *gdbpy_gdberror_exc;
69
70 /* The `gdb.error' base class. */
71 PyObject *gdbpy_gdb_error;
72
73 /* The `gdb.MemoryError' exception. */
74 PyObject *gdbpy_gdb_memory_error;
75
76 /* Architecture and language to be used in callbacks from
77 the Python interpreter. */
78 struct gdbarch *python_gdbarch;
79 const struct language_defn *python_language;
80
81 /* Restore global language and architecture and Python GIL state
82 when leaving the Python interpreter. */
83
84 struct python_env
85 {
86 PyGILState_STATE state;
87 struct gdbarch *gdbarch;
88 const struct language_defn *language;
89 PyObject *error_type, *error_value, *error_traceback;
90 };
91
92 static void
93 restore_python_env (void *p)
94 {
95 struct python_env *env = (struct python_env *)p;
96
97 /* Leftover Python error is forbidden by Python Exception Handling. */
98 if (PyErr_Occurred ())
99 {
100 /* This order is similar to the one calling error afterwards. */
101 gdbpy_print_stack ();
102 warning (_("internal error: Unhandled Python exception"));
103 }
104
105 PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
106
107 PyGILState_Release (env->state);
108 python_gdbarch = env->gdbarch;
109 python_language = env->language;
110 xfree (env);
111 }
112
113 /* Called before entering the Python interpreter to install the
114 current language and architecture to be used for Python values. */
115
116 struct cleanup *
117 ensure_python_env (struct gdbarch *gdbarch,
118 const struct language_defn *language)
119 {
120 struct python_env *env = xmalloc (sizeof *env);
121
122 env->state = PyGILState_Ensure ();
123 env->gdbarch = python_gdbarch;
124 env->language = python_language;
125
126 python_gdbarch = gdbarch;
127 python_language = language;
128
129 /* Save it and ensure ! PyErr_Occurred () afterwards. */
130 PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
131
132 return make_cleanup (restore_python_env, env);
133 }
134
135
136 /* Given a command_line, return a command string suitable for passing
137 to Python. Lines in the string are separated by newlines. The
138 return value is allocated using xmalloc and the caller is
139 responsible for freeing it. */
140
141 static char *
142 compute_python_string (struct command_line *l)
143 {
144 struct command_line *iter;
145 char *script = NULL;
146 int size = 0;
147 int here;
148
149 for (iter = l; iter; iter = iter->next)
150 size += strlen (iter->line) + 1;
151
152 script = xmalloc (size + 1);
153 here = 0;
154 for (iter = l; iter; iter = iter->next)
155 {
156 int len = strlen (iter->line);
157
158 strcpy (&script[here], iter->line);
159 here += len;
160 script[here++] = '\n';
161 }
162 script[here] = '\0';
163 return script;
164 }
165
166 /* Take a command line structure representing a 'python' command, and
167 evaluate its body using the Python interpreter. */
168
169 void
170 eval_python_from_control_command (struct command_line *cmd)
171 {
172 int ret;
173 char *script;
174 struct cleanup *cleanup;
175
176 if (cmd->body_count != 1)
177 error (_("Invalid \"python\" block structure."));
178
179 cleanup = ensure_python_env (get_current_arch (), current_language);
180
181 script = compute_python_string (cmd->body_list[0]);
182 ret = PyRun_SimpleString (script);
183 xfree (script);
184 if (ret)
185 {
186 gdbpy_print_stack ();
187 error (_("Error while executing Python code."));
188 }
189
190 do_cleanups (cleanup);
191 }
192
193 /* Implementation of the gdb "python" command. */
194
195 static void
196 python_command (char *arg, int from_tty)
197 {
198 struct cleanup *cleanup;
199
200 cleanup = ensure_python_env (get_current_arch (), current_language);
201 while (arg && *arg && isspace (*arg))
202 ++arg;
203 if (arg && *arg)
204 {
205 if (PyRun_SimpleString (arg))
206 {
207 gdbpy_print_stack ();
208 error (_("Error while executing Python code."));
209 }
210 }
211 else
212 {
213 struct command_line *l = get_command_line (python_control, "");
214
215 make_cleanup_free_command_lines (&l);
216 execute_control_command_untraced (l);
217 }
218
219 do_cleanups (cleanup);
220 }
221
222 \f
223
224 /* Transform a gdb parameters's value into a Python value. May return
225 NULL (and set a Python exception) on error. Helper function for
226 get_parameter. */
227 PyObject *
228 gdbpy_parameter_value (enum var_types type, void *var)
229 {
230 switch (type)
231 {
232 case var_string:
233 case var_string_noescape:
234 case var_optional_filename:
235 case var_filename:
236 case var_enum:
237 {
238 char *str = * (char **) var;
239
240 if (! str)
241 str = "";
242 return PyString_Decode (str, strlen (str), host_charset (), NULL);
243 }
244
245 case var_boolean:
246 {
247 if (* (int *) var)
248 Py_RETURN_TRUE;
249 else
250 Py_RETURN_FALSE;
251 }
252
253 case var_auto_boolean:
254 {
255 enum auto_boolean ab = * (enum auto_boolean *) var;
256
257 if (ab == AUTO_BOOLEAN_TRUE)
258 Py_RETURN_TRUE;
259 else if (ab == AUTO_BOOLEAN_FALSE)
260 Py_RETURN_FALSE;
261 else
262 Py_RETURN_NONE;
263 }
264
265 case var_integer:
266 if ((* (int *) var) == INT_MAX)
267 Py_RETURN_NONE;
268 /* Fall through. */
269 case var_zinteger:
270 return PyLong_FromLong (* (int *) var);
271
272 case var_uinteger:
273 {
274 unsigned int val = * (unsigned int *) var;
275
276 if (val == UINT_MAX)
277 Py_RETURN_NONE;
278 return PyLong_FromUnsignedLong (val);
279 }
280 }
281
282 return PyErr_Format (PyExc_RuntimeError,
283 _("Programmer error: unhandled type."));
284 }
285
286 /* A Python function which returns a gdb parameter's value as a Python
287 value. */
288
289 PyObject *
290 gdbpy_parameter (PyObject *self, PyObject *args)
291 {
292 struct cmd_list_element *alias, *prefix, *cmd;
293 const char *arg;
294 char *newarg;
295 int found = -1;
296 volatile struct gdb_exception except;
297
298 if (! PyArg_ParseTuple (args, "s", &arg))
299 return NULL;
300
301 newarg = concat ("show ", arg, (char *) NULL);
302
303 TRY_CATCH (except, RETURN_MASK_ALL)
304 {
305 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
306 }
307 xfree (newarg);
308 GDB_PY_HANDLE_EXCEPTION (except);
309 if (!found)
310 return PyErr_Format (PyExc_RuntimeError,
311 _("Could not find parameter `%s'."), arg);
312
313 if (! cmd->var)
314 return PyErr_Format (PyExc_RuntimeError,
315 _("`%s' is not a parameter."), arg);
316 return gdbpy_parameter_value (cmd->var_type, cmd->var);
317 }
318
319 /* Wrapper for target_charset. */
320
321 static PyObject *
322 gdbpy_target_charset (PyObject *self, PyObject *args)
323 {
324 const char *cset = target_charset (python_gdbarch);
325
326 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
327 }
328
329 /* Wrapper for target_wide_charset. */
330
331 static PyObject *
332 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
333 {
334 const char *cset = target_wide_charset (python_gdbarch);
335
336 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
337 }
338
339 /* A Python function which evaluates a string using the gdb CLI. */
340
341 static PyObject *
342 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
343 {
344 const char *arg;
345 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
346 int from_tty, to_string;
347 volatile struct gdb_exception except;
348 static char *keywords[] = {"command", "from_tty", "to_string", NULL };
349 char *result = NULL;
350
351 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
352 &PyBool_Type, &from_tty_obj,
353 &PyBool_Type, &to_string_obj))
354 return NULL;
355
356 from_tty = 0;
357 if (from_tty_obj)
358 {
359 int cmp = PyObject_IsTrue (from_tty_obj);
360 if (cmp < 0)
361 return NULL;
362 from_tty = cmp;
363 }
364
365 to_string = 0;
366 if (to_string_obj)
367 {
368 int cmp = PyObject_IsTrue (to_string_obj);
369 if (cmp < 0)
370 return NULL;
371 to_string = cmp;
372 }
373
374 TRY_CATCH (except, RETURN_MASK_ALL)
375 {
376 /* Copy the argument text in case the command modifies it. */
377 char *copy = xstrdup (arg);
378 struct cleanup *cleanup = make_cleanup (xfree, copy);
379
380 prevent_dont_repeat ();
381 if (to_string)
382 result = execute_command_to_string (copy, from_tty);
383 else
384 {
385 result = NULL;
386 execute_command (copy, from_tty);
387 }
388
389 do_cleanups (cleanup);
390 }
391 GDB_PY_HANDLE_EXCEPTION (except);
392
393 /* Do any commands attached to breakpoint we stopped at. */
394 bpstat_do_actions ();
395
396 if (result)
397 {
398 PyObject *r = PyString_FromString (result);
399 xfree (result);
400 return r;
401 }
402 Py_RETURN_NONE;
403 }
404
405 /* Implementation of gdb.solib_name (Long) -> String.
406 Returns the name of the shared library holding a given address, or None. */
407
408 static PyObject *
409 gdbpy_solib_name (PyObject *self, PyObject *args)
410 {
411 char *soname;
412 PyObject *str_obj;
413 gdb_py_longest pc;
414
415 if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
416 return NULL;
417
418 soname = solib_name_from_address (current_program_space, pc);
419 if (soname)
420 str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
421 else
422 {
423 str_obj = Py_None;
424 Py_INCREF (Py_None);
425 }
426
427 return str_obj;
428 }
429
430 /* A Python function which is a wrapper for decode_line_1. */
431
432 static PyObject *
433 gdbpy_decode_line (PyObject *self, PyObject *args)
434 {
435 struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
436 appease gcc. */
437 struct symtab_and_line sal;
438 const char *arg = NULL;
439 char *copy = NULL;
440 struct cleanup *cleanups;
441 PyObject *result = NULL;
442 PyObject *return_result = NULL;
443 PyObject *unparsed = NULL;
444 volatile struct gdb_exception except;
445
446 if (! PyArg_ParseTuple (args, "|s", &arg))
447 return NULL;
448
449 cleanups = ensure_python_env (get_current_arch (), current_language);
450
451 TRY_CATCH (except, RETURN_MASK_ALL)
452 {
453 if (arg)
454 {
455 copy = xstrdup (arg);
456 make_cleanup (xfree, copy);
457 sals = decode_line_1 (&copy, 0, 0, 0, 0);
458 make_cleanup (xfree, sals.sals);
459 }
460 else
461 {
462 set_default_source_symtab_and_line ();
463 sal = get_current_source_symtab_and_line ();
464 sals.sals = &sal;
465 sals.nelts = 1;
466 }
467 }
468 if (except.reason < 0)
469 {
470 do_cleanups (cleanups);
471 /* We know this will always throw. */
472 GDB_PY_HANDLE_EXCEPTION (except);
473 }
474
475 if (sals.nelts)
476 {
477 int i;
478
479 result = PyTuple_New (sals.nelts);
480 if (! result)
481 goto error;
482 for (i = 0; i < sals.nelts; ++i)
483 {
484 PyObject *obj;
485 char *str;
486
487 obj = symtab_and_line_to_sal_object (sals.sals[i]);
488 if (! obj)
489 {
490 Py_DECREF (result);
491 goto error;
492 }
493
494 PyTuple_SetItem (result, i, obj);
495 }
496 }
497 else
498 {
499 result = Py_None;
500 Py_INCREF (Py_None);
501 }
502
503 return_result = PyTuple_New (2);
504 if (! return_result)
505 {
506 Py_DECREF (result);
507 goto error;
508 }
509
510 if (copy && strlen (copy) > 0)
511 unparsed = PyString_FromString (copy);
512 else
513 {
514 unparsed = Py_None;
515 Py_INCREF (Py_None);
516 }
517
518 PyTuple_SetItem (return_result, 0, unparsed);
519 PyTuple_SetItem (return_result, 1, result);
520
521 do_cleanups (cleanups);
522
523 return return_result;
524
525 error:
526 do_cleanups (cleanups);
527 return NULL;
528 }
529
530 /* Parse a string and evaluate it as an expression. */
531 static PyObject *
532 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
533 {
534 const char *expr_str;
535 struct value *result = NULL;
536 volatile struct gdb_exception except;
537
538 if (!PyArg_ParseTuple (args, "s", &expr_str))
539 return NULL;
540
541 TRY_CATCH (except, RETURN_MASK_ALL)
542 {
543 char *copy = xstrdup (expr_str);
544 struct cleanup *cleanup = make_cleanup (xfree, copy);
545
546 result = parse_and_eval (copy);
547 do_cleanups (cleanup);
548 }
549 GDB_PY_HANDLE_EXCEPTION (except);
550
551 return value_to_value_object (result);
552 }
553
554 /* Read a file as Python code. STREAM is the input file; FILE is the
555 name of the file.
556 STREAM is not closed, that is the caller's responsibility. */
557
558 void
559 source_python_script (FILE *stream, const char *file)
560 {
561 struct cleanup *cleanup;
562
563 cleanup = ensure_python_env (get_current_arch (), current_language);
564
565 /* Note: If an exception occurs python will print the traceback and
566 clear the error indicator. */
567 PyRun_SimpleFile (stream, file);
568
569 do_cleanups (cleanup);
570 }
571
572 \f
573
574 /* Posting and handling events. */
575
576 /* A single event. */
577 struct gdbpy_event
578 {
579 /* The Python event. This is just a callable object. */
580 PyObject *event;
581 /* The next event. */
582 struct gdbpy_event *next;
583 };
584
585 /* All pending events. */
586 static struct gdbpy_event *gdbpy_event_list;
587 /* The final link of the event list. */
588 static struct gdbpy_event **gdbpy_event_list_end;
589
590 /* We use a file handler, and not an async handler, so that we can
591 wake up the main thread even when it is blocked in poll(). */
592 static struct serial *gdbpy_event_fds[2];
593
594 /* The file handler callback. This reads from the internal pipe, and
595 then processes the Python event queue. This will always be run in
596 the main gdb thread. */
597
598 static void
599 gdbpy_run_events (struct serial *scb, void *context)
600 {
601 struct cleanup *cleanup;
602 int r;
603
604 cleanup = ensure_python_env (get_current_arch (), current_language);
605
606 /* Flush the fd. Do this before flushing the events list, so that
607 any new event post afterwards is sure to re-awake the event
608 loop. */
609 while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
610 ;
611
612 while (gdbpy_event_list)
613 {
614 /* Dispatching the event might push a new element onto the event
615 loop, so we update here "atomically enough". */
616 struct gdbpy_event *item = gdbpy_event_list;
617 gdbpy_event_list = gdbpy_event_list->next;
618 if (gdbpy_event_list == NULL)
619 gdbpy_event_list_end = &gdbpy_event_list;
620
621 /* Ignore errors. */
622 if (PyObject_CallObject (item->event, NULL) == NULL)
623 PyErr_Clear ();
624
625 Py_DECREF (item->event);
626 xfree (item);
627 }
628
629 do_cleanups (cleanup);
630 }
631
632 /* Submit an event to the gdb thread. */
633 static PyObject *
634 gdbpy_post_event (PyObject *self, PyObject *args)
635 {
636 struct gdbpy_event *event;
637 PyObject *func;
638 int wakeup;
639
640 if (!PyArg_ParseTuple (args, "O", &func))
641 return NULL;
642
643 if (!PyCallable_Check (func))
644 {
645 PyErr_SetString (PyExc_RuntimeError,
646 _("Posted event is not callable"));
647 return NULL;
648 }
649
650 Py_INCREF (func);
651
652 /* From here until the end of the function, we have the GIL, so we
653 can operate on our global data structures without worrying. */
654 wakeup = gdbpy_event_list == NULL;
655
656 event = XNEW (struct gdbpy_event);
657 event->event = func;
658 event->next = NULL;
659 *gdbpy_event_list_end = event;
660 gdbpy_event_list_end = &event->next;
661
662 /* Wake up gdb when needed. */
663 if (wakeup)
664 {
665 char c = 'q'; /* Anything. */
666
667 if (serial_write (gdbpy_event_fds[1], &c, 1))
668 return PyErr_SetFromErrno (PyExc_IOError);
669 }
670
671 Py_RETURN_NONE;
672 }
673
674 /* Initialize the Python event handler. */
675 static void
676 gdbpy_initialize_events (void)
677 {
678 if (serial_pipe (gdbpy_event_fds) == 0)
679 {
680 gdbpy_event_list_end = &gdbpy_event_list;
681 serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
682 }
683 }
684
685 /* Printing. */
686
687 /* A python function to write a single string using gdb's filtered
688 output stream . The optional keyword STREAM can be used to write
689 to a particular stream. The default stream is to gdb_stdout. */
690
691 static PyObject *
692 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
693 {
694 const char *arg;
695 static char *keywords[] = {"text", "stream", NULL };
696 int stream_type = 0;
697
698 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
699 &stream_type))
700 return NULL;
701
702 switch (stream_type)
703 {
704 case 1:
705 {
706 fprintf_filtered (gdb_stderr, "%s", arg);
707 break;
708 }
709 case 2:
710 {
711 fprintf_filtered (gdb_stdlog, "%s", arg);
712 break;
713 }
714 default:
715 fprintf_filtered (gdb_stdout, "%s", arg);
716 }
717
718 Py_RETURN_NONE;
719 }
720
721 /* A python function to flush a gdb stream. The optional keyword
722 STREAM can be used to flush a particular stream. The default stream
723 is gdb_stdout. */
724
725 static PyObject *
726 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
727 {
728 static char *keywords[] = {"stream", NULL };
729 int stream_type = 0;
730
731 if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
732 &stream_type))
733 return NULL;
734
735 switch (stream_type)
736 {
737 case 1:
738 {
739 gdb_flush (gdb_stderr);
740 break;
741 }
742 case 2:
743 {
744 gdb_flush (gdb_stdlog);
745 break;
746 }
747 default:
748 gdb_flush (gdb_stdout);
749 }
750
751 Py_RETURN_NONE;
752 }
753
754 /* Print a python exception trace, or print nothing and clear the
755 python exception, depending on gdbpy_should_print_stack. Only call
756 this if a python exception is set. */
757 void
758 gdbpy_print_stack (void)
759 {
760 if (gdbpy_should_print_stack)
761 {
762 PyErr_Print ();
763 /* PyErr_Print doesn't necessarily end output with a newline.
764 This works because Python's stdout/stderr is fed through
765 printf_filtered. */
766 begin_line ();
767 }
768 else
769 PyErr_Clear ();
770 }
771
772 \f
773
774 /* Return the current Progspace.
775 There always is one. */
776
777 static PyObject *
778 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
779 {
780 PyObject *result;
781
782 result = pspace_to_pspace_object (current_program_space);
783 if (result)
784 Py_INCREF (result);
785 return result;
786 }
787
788 /* Return a sequence holding all the Progspaces. */
789
790 static PyObject *
791 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
792 {
793 struct program_space *ps;
794 PyObject *list;
795
796 list = PyList_New (0);
797 if (!list)
798 return NULL;
799
800 ALL_PSPACES (ps)
801 {
802 PyObject *item = pspace_to_pspace_object (ps);
803
804 if (!item || PyList_Append (list, item) == -1)
805 {
806 Py_DECREF (list);
807 return NULL;
808 }
809 }
810
811 return list;
812 }
813
814 \f
815
816 /* The "current" objfile. This is set when gdb detects that a new
817 objfile has been loaded. It is only set for the duration of a call to
818 source_python_script_for_objfile; it is NULL at other times. */
819 static struct objfile *gdbpy_current_objfile;
820
821 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
822 Python code. */
823
824 void
825 source_python_script_for_objfile (struct objfile *objfile,
826 FILE *stream, const char *file)
827 {
828 struct cleanup *cleanups;
829
830 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
831 gdbpy_current_objfile = objfile;
832
833 /* Note: If an exception occurs python will print the traceback and
834 clear the error indicator. */
835 PyRun_SimpleFile (stream, file);
836
837 do_cleanups (cleanups);
838 gdbpy_current_objfile = NULL;
839 }
840
841 /* Return the current Objfile, or None if there isn't one. */
842
843 static PyObject *
844 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
845 {
846 PyObject *result;
847
848 if (! gdbpy_current_objfile)
849 Py_RETURN_NONE;
850
851 result = objfile_to_objfile_object (gdbpy_current_objfile);
852 if (result)
853 Py_INCREF (result);
854 return result;
855 }
856
857 /* Return a sequence holding all the Objfiles. */
858
859 static PyObject *
860 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
861 {
862 struct objfile *objf;
863 PyObject *list;
864
865 list = PyList_New (0);
866 if (!list)
867 return NULL;
868
869 ALL_OBJFILES (objf)
870 {
871 PyObject *item = objfile_to_objfile_object (objf);
872
873 if (!item || PyList_Append (list, item) == -1)
874 {
875 Py_DECREF (list);
876 return NULL;
877 }
878 }
879
880 return list;
881 }
882
883 #else /* HAVE_PYTHON */
884
885 /* Dummy implementation of the gdb "python" command. */
886
887 static void
888 python_command (char *arg, int from_tty)
889 {
890 while (arg && *arg && isspace (*arg))
891 ++arg;
892 if (arg && *arg)
893 error (_("Python scripting is not supported in this copy of GDB."));
894 else
895 {
896 struct command_line *l = get_command_line (python_control, "");
897 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
898
899 execute_control_command_untraced (l);
900 do_cleanups (cleanups);
901 }
902 }
903
904 void
905 eval_python_from_control_command (struct command_line *cmd)
906 {
907 error (_("Python scripting is not supported in this copy of GDB."));
908 }
909
910 void
911 source_python_script (FILE *stream, const char *file)
912 {
913 throw_error (UNSUPPORTED_ERROR,
914 _("Python scripting is not supported in this copy of GDB."));
915 }
916
917 int
918 gdbpy_should_stop (struct breakpoint_object *bp_obj)
919 {
920 internal_error (__FILE__, __LINE__,
921 _("gdbpy_should_stop called when Python scripting is " \
922 "not supported."));
923 }
924
925 int
926 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
927 {
928 internal_error (__FILE__, __LINE__,
929 _("gdbpy_breakpoint_has_py_cond called when Python " \
930 "scripting is not supported."));
931 }
932
933 #endif /* HAVE_PYTHON */
934
935 \f
936
937 /* Lists for 'maint set python' commands. */
938
939 static struct cmd_list_element *maint_set_python_list;
940 static struct cmd_list_element *maint_show_python_list;
941
942 /* Lists for 'set python' commands. */
943
944 static struct cmd_list_element *user_set_python_list;
945 static struct cmd_list_element *user_show_python_list;
946
947 /* Function for use by 'maint set python' prefix command. */
948
949 static void
950 maint_set_python (char *args, int from_tty)
951 {
952 help_list (maint_set_python_list, "maintenance set python ",
953 class_deprecated, gdb_stdout);
954 }
955
956 /* Function for use by 'maint show python' prefix command. */
957
958 static void
959 maint_show_python (char *args, int from_tty)
960 {
961 cmd_show_list (maint_show_python_list, from_tty, "");
962 }
963
964 /* Function for use by 'set python' prefix command. */
965
966 static void
967 user_set_python (char *args, int from_tty)
968 {
969 help_list (user_set_python_list, "set python ", all_commands,
970 gdb_stdout);
971 }
972
973 /* Function for use by 'show python' prefix command. */
974
975 static void
976 user_show_python (char *args, int from_tty)
977 {
978 cmd_show_list (user_show_python_list, from_tty, "");
979 }
980
981 /* Initialize the Python code. */
982
983 /* Provide a prototype to silence -Wmissing-prototypes. */
984 extern initialize_file_ftype _initialize_python;
985
986 void
987 _initialize_python (void)
988 {
989 char *cmd_name;
990 struct cmd_list_element *cmd;
991
992 add_com ("python", class_obscure, python_command,
993 #ifdef HAVE_PYTHON
994 _("\
995 Evaluate a Python command.\n\
996 \n\
997 The command can be given as an argument, for instance:\n\
998 \n\
999 python print 23\n\
1000 \n\
1001 If no argument is given, the following lines are read and used\n\
1002 as the Python commands. Type a line containing \"end\" to indicate\n\
1003 the end of the command.")
1004 #else /* HAVE_PYTHON */
1005 _("\
1006 Evaluate a Python command.\n\
1007 \n\
1008 Python scripting is not supported in this copy of GDB.\n\
1009 This command is only a placeholder.")
1010 #endif /* HAVE_PYTHON */
1011 );
1012
1013 add_prefix_cmd ("python", no_class, maint_show_python,
1014 _("Prefix command for python maintenance settings."),
1015 &maint_show_python_list, "maintenance show python ", 0,
1016 &maintenance_show_cmdlist);
1017 add_prefix_cmd ("python", no_class, maint_set_python,
1018 _("Prefix command for python maintenance settings."),
1019 &maint_set_python_list, "maintenance set python ", 0,
1020 &maintenance_set_cmdlist);
1021
1022 add_setshow_boolean_cmd ("print-stack", class_maintenance,
1023 &gdbpy_should_print_stack, _("\
1024 Enable or disable printing of Python stack dump on error."), _("\
1025 Show whether Python stack will be printed on error."), _("\
1026 Enables or disables printing of Python stack traces."),
1027 NULL, NULL,
1028 &maint_set_python_list,
1029 &maint_show_python_list);
1030
1031 /* Deprecate maint set/show python print-stack in favour of
1032 non-maintenance alternatives. */
1033 cmd_name = "print-stack";
1034 cmd = lookup_cmd (&cmd_name, maint_set_python_list, "", -1, 0);
1035 deprecate_cmd (cmd, "set python print-stack");
1036 cmd_name = "print-stack"; /* Reset name. */
1037 cmd = lookup_cmd (&cmd_name, maint_show_python_list, "", -1, 0);
1038 deprecate_cmd (cmd, "show python print-stack");
1039
1040 /* Add set/show python print-stack. */
1041 add_prefix_cmd ("python", no_class, user_show_python,
1042 _("Prefix command for python preference settings."),
1043 &user_show_python_list, "show python ", 0,
1044 &showlist);
1045
1046 add_prefix_cmd ("python", no_class, user_set_python,
1047 _("Prefix command for python preference settings."),
1048 &user_set_python_list, "set python ", 0,
1049 &setlist);
1050
1051 add_setshow_boolean_cmd ("print-stack", no_class,
1052 &gdbpy_should_print_stack, _("\
1053 Enable or disable printing of Python stack dump on error."), _("\
1054 Show whether Python stack will be printed on error."), _("\
1055 Enables or disables printing of Python stack traces."),
1056 NULL, NULL,
1057 &user_set_python_list,
1058 &user_show_python_list);
1059
1060 #ifdef HAVE_PYTHON
1061 #ifdef WITH_PYTHON_PATH
1062 /* Work around problem where python gets confused about where it is,
1063 and then can't find its libraries, etc.
1064 NOTE: Python assumes the following layout:
1065 /foo/bin/python
1066 /foo/lib/pythonX.Y/...
1067 This must be done before calling Py_Initialize. */
1068 Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
1069 SLASH_STRING, "python", NULL));
1070 #endif
1071
1072 Py_Initialize ();
1073 PyEval_InitThreads ();
1074
1075 gdb_module = Py_InitModule ("gdb", GdbMethods);
1076
1077 /* The casts to (char*) are for python 2.4. */
1078 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
1079 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
1080 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1081 (char*) target_name);
1082
1083 /* Add stream constants. */
1084 PyModule_AddIntConstant (gdb_module, "STDOUT", 0);
1085 PyModule_AddIntConstant (gdb_module, "STDERR", 1);
1086 PyModule_AddIntConstant (gdb_module, "STDLOG", 2);
1087
1088 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1089 script below is run (depending on order of _initialize_* functions).
1090 Define the initial value of gdb.PYTHONDIR here. */
1091 {
1092 char *gdb_pythondir;
1093
1094 gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
1095 PyModule_AddStringConstant (gdb_module, "PYTHONDIR", gdb_pythondir);
1096 xfree (gdb_pythondir);
1097 }
1098
1099 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1100 PyModule_AddObject (gdb_module, "error", gdbpy_gdb_error);
1101
1102 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1103 gdbpy_gdb_error, NULL);
1104 PyModule_AddObject (gdb_module, "MemoryError", gdbpy_gdb_memory_error);
1105
1106 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1107 PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
1108
1109 gdbpy_initialize_auto_load ();
1110 gdbpy_initialize_values ();
1111 gdbpy_initialize_frames ();
1112 gdbpy_initialize_commands ();
1113 gdbpy_initialize_symbols ();
1114 gdbpy_initialize_symtabs ();
1115 gdbpy_initialize_blocks ();
1116 gdbpy_initialize_functions ();
1117 gdbpy_initialize_parameters ();
1118 gdbpy_initialize_types ();
1119 gdbpy_initialize_pspace ();
1120 gdbpy_initialize_objfile ();
1121 gdbpy_initialize_breakpoints ();
1122 gdbpy_initialize_lazy_string ();
1123 gdbpy_initialize_thread ();
1124 gdbpy_initialize_inferior ();
1125 gdbpy_initialize_events ();
1126
1127 gdbpy_initialize_eventregistry ();
1128 gdbpy_initialize_py_events ();
1129 gdbpy_initialize_event ();
1130 gdbpy_initialize_stop_event ();
1131 gdbpy_initialize_signal_event ();
1132 gdbpy_initialize_breakpoint_event ();
1133 gdbpy_initialize_continue_event ();
1134 gdbpy_initialize_exited_event ();
1135 gdbpy_initialize_thread_event ();
1136
1137 PyRun_SimpleString ("import gdb");
1138 PyRun_SimpleString ("gdb.pretty_printers = []");
1139
1140 gdbpy_to_string_cst = PyString_FromString ("to_string");
1141 gdbpy_children_cst = PyString_FromString ("children");
1142 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1143 gdbpy_doc_cst = PyString_FromString ("__doc__");
1144 gdbpy_enabled_cst = PyString_FromString ("enabled");
1145 gdbpy_value_cst = PyString_FromString ("value");
1146
1147 /* Release the GIL while gdb runs. */
1148 PyThreadState_Swap (NULL);
1149 PyEval_ReleaseLock ();
1150
1151 #endif /* HAVE_PYTHON */
1152 }
1153
1154 #ifdef HAVE_PYTHON
1155
1156 /* Perform the remaining python initializations.
1157 These must be done after GDB is at least mostly initialized.
1158 E.g., The "info pretty-printer" command needs the "info" prefix
1159 command installed. */
1160
1161 void
1162 finish_python_initialization (void)
1163 {
1164 struct cleanup *cleanup;
1165
1166 cleanup = ensure_python_env (get_current_arch (), current_language);
1167
1168 PyRun_SimpleString ("\
1169 import os\n\
1170 import sys\n\
1171 \n\
1172 class GdbOutputFile:\n\
1173 def close(self):\n\
1174 # Do nothing.\n\
1175 return None\n\
1176 \n\
1177 def isatty(self):\n\
1178 return False\n\
1179 \n\
1180 def write(self, s):\n\
1181 gdb.write(s, stream=gdb.STDOUT)\n \
1182 \n\
1183 def writelines(self, iterable):\n\
1184 for line in iterable:\n\
1185 self.write(line)\n\
1186 \n\
1187 def flush(self):\n\
1188 gdb.flush()\n\
1189 \n\
1190 sys.stdout = GdbOutputFile()\n\
1191 \n\
1192 class GdbOutputErrorFile:\n\
1193 def close(self):\n\
1194 # Do nothing.\n\
1195 return None\n\
1196 \n\
1197 def isatty(self):\n\
1198 return False\n\
1199 \n\
1200 def write(self, s):\n\
1201 gdb.write(s, stream=gdb.STDERR)\n \
1202 \n\
1203 def writelines(self, iterable):\n\
1204 for line in iterable:\n\
1205 self.write(line)\n \
1206 \n\
1207 def flush(self):\n\
1208 gdb.flush()\n\
1209 \n\
1210 sys.stderr = GdbOutputErrorFile()\n\
1211 \n\
1212 # Ideally this would live in the gdb module, but it's intentionally written\n\
1213 # in python, and we need this to bootstrap the gdb module.\n\
1214 \n\
1215 def GdbSetPythonDirectory (dir):\n\
1216 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1217 old_dir = gdb.PYTHONDIR\n\
1218 gdb.PYTHONDIR = dir\n\
1219 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1220 # that directory name at the start of sys.path to allow the Python\n\
1221 # interpreter to find them.\n\
1222 if old_dir in sys.path:\n\
1223 sys.path.remove (old_dir)\n\
1224 sys.path.insert (0, gdb.PYTHONDIR)\n\
1225 \n\
1226 # Tell python where to find submodules of gdb.\n\
1227 gdb.__path__ = [gdb.PYTHONDIR + '/gdb']\n\
1228 \n\
1229 # The gdb module is implemented in C rather than in Python. As a result,\n\
1230 # the associated __init.py__ script is not not executed by default when\n\
1231 # the gdb module gets imported. Execute that script manually if it\n\
1232 # exists.\n\
1233 ipy = gdb.PYTHONDIR + '/gdb/__init__.py'\n\
1234 if os.path.exists (ipy):\n\
1235 execfile (ipy)\n\
1236 \n\
1237 # Install the default gdb.PYTHONDIR.\n\
1238 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1239 ");
1240
1241 do_cleanups (cleanup);
1242 }
1243
1244 #endif /* HAVE_PYTHON */
1245
1246 \f
1247
1248 #ifdef HAVE_PYTHON
1249
1250 static PyMethodDef GdbMethods[] =
1251 {
1252 { "history", gdbpy_history, METH_VARARGS,
1253 "Get a value from history" },
1254 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1255 "Execute a gdb command" },
1256 { "parameter", gdbpy_parameter, METH_VARARGS,
1257 "Return a gdb parameter's value" },
1258
1259 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1260 "Return a tuple of all breakpoint objects" },
1261
1262 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1263 "Find the default visualizer for a Value." },
1264
1265 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1266 "Return the current Progspace." },
1267 { "progspaces", gdbpy_progspaces, METH_NOARGS,
1268 "Return a sequence of all progspaces." },
1269
1270 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1271 "Return the current Objfile being loaded, or None." },
1272 { "objfiles", gdbpy_objfiles, METH_NOARGS,
1273 "Return a sequence of all loaded objfiles." },
1274
1275 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
1276 "newest_frame () -> gdb.Frame.\n\
1277 Return the newest frame object." },
1278 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1279 "selected_frame () -> gdb.Frame.\n\
1280 Return the selected frame object." },
1281 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1282 "stop_reason_string (Integer) -> String.\n\
1283 Return a string explaining unwind stop reason." },
1284
1285 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1286 METH_VARARGS | METH_KEYWORDS,
1287 "lookup_type (name [, block]) -> type\n\
1288 Return a Type corresponding to the given name." },
1289 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1290 METH_VARARGS | METH_KEYWORDS,
1291 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1292 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1293 a boolean indicating if name is a field of the current implied argument\n\
1294 `this' (when the current language is object-oriented)." },
1295 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
1296 METH_VARARGS | METH_KEYWORDS,
1297 "lookup_global_symbol (name [, domain]) -> symbol\n\
1298 Return the symbol corresponding to the given name (or None)." },
1299 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1300 "Return the block containing the given pc value, or None." },
1301 { "solib_name", gdbpy_solib_name, METH_VARARGS,
1302 "solib_name (Long) -> String.\n\
1303 Return the name of the shared library holding a given address, or None." },
1304 { "decode_line", gdbpy_decode_line, METH_VARARGS,
1305 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1306 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1307 The first element contains any unparsed portion of the String parameter\n\
1308 (or None if the string was fully parsed). The second element contains\n\
1309 a tuple that contains all the locations that match, represented as\n\
1310 gdb.Symtab_and_line objects (or None)."},
1311 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1312 "parse_and_eval (String) -> Value.\n\
1313 Parse String as an expression, evaluate it, and return the result as a Value."
1314 },
1315
1316 { "post_event", gdbpy_post_event, METH_VARARGS,
1317 "Post an event into gdb's event loop." },
1318
1319 { "target_charset", gdbpy_target_charset, METH_NOARGS,
1320 "target_charset () -> string.\n\
1321 Return the name of the current target charset." },
1322 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1323 "target_wide_charset () -> string.\n\
1324 Return the name of the current target wide charset." },
1325
1326 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1327 "string_to_argv (String) -> Array.\n\
1328 Parse String and return an argv-like array.\n\
1329 Arguments are separate by spaces and may be quoted."
1330 },
1331 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
1332 "Write a string using gdb's filtered stream." },
1333 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
1334 "Flush gdb's filtered stdout stream." },
1335 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1336 "selected_thread () -> gdb.InferiorThread.\n\
1337 Return the selected thread object." },
1338 { "inferiors", gdbpy_inferiors, METH_NOARGS,
1339 "inferiors () -> (gdb.Inferior, ...).\n\
1340 Return a tuple containing all inferiors." },
1341 {NULL, NULL, 0, NULL}
1342 };
1343
1344 #endif /* HAVE_PYTHON */