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