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