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