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