2010-05-17 Michael Snyder <msnyder@vmware.com>
[binutils-gdb.git] / gdb / python / python.c
1 /* General python/gdb code
2
3 Copyright (C) 2008, 2009, 2010 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "command.h"
23 #include "ui-out.h"
24 #include "cli/cli-script.h"
25 #include "gdbcmd.h"
26 #include "progspace.h"
27 #include "objfiles.h"
28 #include "value.h"
29 #include "language.h"
30 #include "exceptions.h"
31
32 #include <ctype.h>
33
34 /* True if we should print the stack when catching a Python error,
35 false otherwise. */
36 static int gdbpy_should_print_stack = 1;
37
38 #ifdef HAVE_PYTHON
39
40 #include "python.h"
41 #include "libiberty.h"
42 #include "cli/cli-decode.h"
43 #include "charset.h"
44 #include "top.h"
45 #include "python-internal.h"
46 #include "version.h"
47 #include "target.h"
48 #include "gdbthread.h"
49
50 static PyMethodDef GdbMethods[];
51
52 PyObject *gdb_module;
53
54 /* Some string constants we may wish to use. */
55 PyObject *gdbpy_to_string_cst;
56 PyObject *gdbpy_children_cst;
57 PyObject *gdbpy_display_hint_cst;
58 PyObject *gdbpy_doc_cst;
59
60
61 /* Architecture and language to be used in callbacks from
62 the Python interpreter. */
63 struct gdbarch *python_gdbarch;
64 const struct language_defn *python_language;
65
66 /* Restore global language and architecture and Python GIL state
67 when leaving the Python interpreter. */
68
69 struct python_env
70 {
71 PyGILState_STATE state;
72 struct gdbarch *gdbarch;
73 const struct language_defn *language;
74 };
75
76 static void
77 restore_python_env (void *p)
78 {
79 struct python_env *env = (struct python_env *)p;
80
81 PyGILState_Release (env->state);
82 python_gdbarch = env->gdbarch;
83 python_language = env->language;
84 xfree (env);
85 }
86
87 /* Called before entering the Python interpreter to install the
88 current language and architecture to be used for Python values. */
89
90 struct cleanup *
91 ensure_python_env (struct gdbarch *gdbarch,
92 const struct language_defn *language)
93 {
94 struct python_env *env = xmalloc (sizeof *env);
95
96 env->state = PyGILState_Ensure ();
97 env->gdbarch = python_gdbarch;
98 env->language = python_language;
99
100 python_gdbarch = gdbarch;
101 python_language = language;
102
103 return make_cleanup (restore_python_env, env);
104 }
105
106
107 /* Given a command_line, return a command string suitable for passing
108 to Python. Lines in the string are separated by newlines. The
109 return value is allocated using xmalloc and the caller is
110 responsible for freeing it. */
111
112 static char *
113 compute_python_string (struct command_line *l)
114 {
115 struct command_line *iter;
116 char *script = NULL;
117 int size = 0;
118 int here;
119
120 for (iter = l; iter; iter = iter->next)
121 size += strlen (iter->line) + 1;
122
123 script = xmalloc (size + 1);
124 here = 0;
125 for (iter = l; iter; iter = iter->next)
126 {
127 int len = strlen (iter->line);
128
129 strcpy (&script[here], iter->line);
130 here += len;
131 script[here++] = '\n';
132 }
133 script[here] = '\0';
134 return script;
135 }
136
137 /* Take a command line structure representing a 'python' command, and
138 evaluate its body using the Python interpreter. */
139
140 void
141 eval_python_from_control_command (struct command_line *cmd)
142 {
143 int ret;
144 char *script;
145 struct cleanup *cleanup;
146
147 if (cmd->body_count != 1)
148 error (_("Invalid \"python\" block structure."));
149
150 cleanup = ensure_python_env (get_current_arch (), current_language);
151
152 script = compute_python_string (cmd->body_list[0]);
153 ret = PyRun_SimpleString (script);
154 xfree (script);
155 if (ret)
156 {
157 gdbpy_print_stack ();
158 error (_("Error while executing Python code."));
159 }
160
161 do_cleanups (cleanup);
162 }
163
164 /* Implementation of the gdb "python" command. */
165
166 static void
167 python_command (char *arg, int from_tty)
168 {
169 struct cleanup *cleanup;
170
171 cleanup = ensure_python_env (get_current_arch (), current_language);
172 while (arg && *arg && isspace (*arg))
173 ++arg;
174 if (arg && *arg)
175 {
176 if (PyRun_SimpleString (arg))
177 {
178 gdbpy_print_stack ();
179 error (_("Error while executing Python code."));
180 }
181 }
182 else
183 {
184 struct command_line *l = get_command_line (python_control, "");
185
186 make_cleanup_free_command_lines (&l);
187 execute_control_command_untraced (l);
188 }
189
190 do_cleanups (cleanup);
191 }
192
193 \f
194
195 /* Transform a gdb parameters's value into a Python value. May return
196 NULL (and set a Python exception) on error. Helper function for
197 get_parameter. */
198 PyObject *
199 gdbpy_parameter_value (enum var_types type, void *var)
200 {
201 switch (type)
202 {
203 case var_string:
204 case var_string_noescape:
205 case var_optional_filename:
206 case var_filename:
207 case var_enum:
208 {
209 char *str = * (char **) var;
210
211 if (! str)
212 str = "";
213 return PyString_Decode (str, strlen (str), host_charset (), NULL);
214 }
215
216 case var_boolean:
217 {
218 if (* (int *) var)
219 Py_RETURN_TRUE;
220 else
221 Py_RETURN_FALSE;
222 }
223
224 case var_auto_boolean:
225 {
226 enum auto_boolean ab = * (enum auto_boolean *) var;
227
228 if (ab == AUTO_BOOLEAN_TRUE)
229 Py_RETURN_TRUE;
230 else if (ab == AUTO_BOOLEAN_FALSE)
231 Py_RETURN_FALSE;
232 else
233 Py_RETURN_NONE;
234 }
235
236 case var_integer:
237 if ((* (int *) var) == INT_MAX)
238 Py_RETURN_NONE;
239 /* Fall through. */
240 case var_zinteger:
241 return PyLong_FromLong (* (int *) var);
242
243 case var_uinteger:
244 {
245 unsigned int val = * (unsigned int *) var;
246
247 if (val == UINT_MAX)
248 Py_RETURN_NONE;
249 return PyLong_FromUnsignedLong (val);
250 }
251 }
252
253 return PyErr_Format (PyExc_RuntimeError,
254 _("Programmer error: unhandled type."));
255 }
256
257 /* A Python function which returns a gdb parameter's value as a Python
258 value. */
259
260 PyObject *
261 gdbpy_parameter (PyObject *self, PyObject *args)
262 {
263 struct cmd_list_element *alias, *prefix, *cmd;
264 char *arg, *newarg;
265 int found = -1;
266 volatile struct gdb_exception except;
267
268 if (! PyArg_ParseTuple (args, "s", &arg))
269 return NULL;
270
271 newarg = concat ("show ", arg, (char *) NULL);
272
273 TRY_CATCH (except, RETURN_MASK_ALL)
274 {
275 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
276 }
277 xfree (newarg);
278 GDB_PY_HANDLE_EXCEPTION (except);
279 if (!found)
280 return PyErr_Format (PyExc_RuntimeError,
281 _("Could not find parameter `%s'."), arg);
282
283 if (! cmd->var)
284 return PyErr_Format (PyExc_RuntimeError,
285 _("`%s' is not a parameter."), arg);
286 return gdbpy_parameter_value (cmd->var_type, cmd->var);
287 }
288
289 /* Wrapper for target_charset. */
290
291 static PyObject *
292 gdbpy_target_charset (PyObject *self, PyObject *args)
293 {
294 const char *cset = target_charset (python_gdbarch);
295
296 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
297 }
298
299 /* Wrapper for target_wide_charset. */
300
301 static PyObject *
302 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
303 {
304 const char *cset = target_wide_charset (python_gdbarch);
305
306 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
307 }
308
309 /* A Python function which evaluates a string using the gdb CLI. */
310
311 static PyObject *
312 execute_gdb_command (PyObject *self, PyObject *args)
313 {
314 char *arg;
315 PyObject *from_tty_obj = NULL;
316 int from_tty;
317 int cmp;
318 volatile struct gdb_exception except;
319
320 if (! PyArg_ParseTuple (args, "s|O!", &arg, &PyBool_Type, &from_tty_obj))
321 return NULL;
322
323 from_tty = 0;
324 if (from_tty_obj)
325 {
326 cmp = PyObject_IsTrue (from_tty_obj);
327 if (cmp < 0)
328 return NULL;
329 from_tty = cmp;
330 }
331
332 TRY_CATCH (except, RETURN_MASK_ALL)
333 {
334 /* Copy the argument text in case the command modifies it. */
335 char *copy = xstrdup (arg);
336 struct cleanup *cleanup = make_cleanup (xfree, copy);
337
338 execute_command (copy, from_tty);
339 do_cleanups (cleanup);
340 }
341 GDB_PY_HANDLE_EXCEPTION (except);
342
343 /* Do any commands attached to breakpoint we stopped at. */
344 bpstat_do_actions ();
345
346 Py_RETURN_NONE;
347 }
348
349 /* Parse a string and evaluate it as an expression. */
350 static PyObject *
351 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
352 {
353 char *expr_str;
354 struct value *result = NULL;
355 volatile struct gdb_exception except;
356
357 if (!PyArg_ParseTuple (args, "s", &expr_str))
358 return NULL;
359
360 TRY_CATCH (except, RETURN_MASK_ALL)
361 {
362 result = parse_and_eval (expr_str);
363 }
364 GDB_PY_HANDLE_EXCEPTION (except);
365
366 return value_to_value_object (result);
367 }
368
369 /* Read a file as Python code. STREAM is the input file; FILE is the
370 name of the file.
371 STREAM is not closed, that is the caller's responsibility. */
372
373 void
374 source_python_script (FILE *stream, const char *file)
375 {
376 struct cleanup *cleanup;
377
378 cleanup = ensure_python_env (get_current_arch (), current_language);
379
380 PyRun_SimpleFile (stream, file);
381
382 do_cleanups (cleanup);
383 }
384
385 \f
386
387 /* Printing. */
388
389 /* A python function to write a single string using gdb's filtered
390 output stream. */
391 static PyObject *
392 gdbpy_write (PyObject *self, PyObject *args)
393 {
394 char *arg;
395
396 if (! PyArg_ParseTuple (args, "s", &arg))
397 return NULL;
398 printf_filtered ("%s", arg);
399 Py_RETURN_NONE;
400 }
401
402 /* A python function to flush gdb's filtered output stream. */
403 static PyObject *
404 gdbpy_flush (PyObject *self, PyObject *args)
405 {
406 gdb_flush (gdb_stdout);
407 Py_RETURN_NONE;
408 }
409
410 /* Print a python exception trace, or print nothing and clear the
411 python exception, depending on gdbpy_should_print_stack. Only call
412 this if a python exception is set. */
413 void
414 gdbpy_print_stack (void)
415 {
416 if (gdbpy_should_print_stack)
417 PyErr_Print ();
418 else
419 PyErr_Clear ();
420 }
421
422 \f
423
424 /* Return the current Progspace.
425 There always is one. */
426
427 static PyObject *
428 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
429 {
430 PyObject *result;
431
432 result = pspace_to_pspace_object (current_program_space);
433 if (result)
434 Py_INCREF (result);
435 return result;
436 }
437
438 /* Return a sequence holding all the Progspaces. */
439
440 static PyObject *
441 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
442 {
443 struct program_space *ps;
444 PyObject *list;
445
446 list = PyList_New (0);
447 if (!list)
448 return NULL;
449
450 ALL_PSPACES (ps)
451 {
452 PyObject *item = pspace_to_pspace_object (ps);
453
454 if (!item || PyList_Append (list, item) == -1)
455 {
456 Py_DECREF (list);
457 return NULL;
458 }
459 }
460
461 return list;
462 }
463
464 \f
465
466 /* The "current" objfile. This is set when gdb detects that a new
467 objfile has been loaded. It is only set for the duration of a call to
468 source_python_script_for_objfile; it is NULL at other times. */
469 static struct objfile *gdbpy_current_objfile;
470
471 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
472 Python code. */
473
474 void
475 source_python_script_for_objfile (struct objfile *objfile,
476 FILE *stream, const char *file)
477 {
478 struct cleanup *cleanups;
479
480 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
481 gdbpy_current_objfile = objfile;
482
483 /* We don't want to throw an exception here -- but the user
484 would like to know that something went wrong. */
485 if (PyRun_SimpleFile (stream, file))
486 gdbpy_print_stack ();
487
488 do_cleanups (cleanups);
489 gdbpy_current_objfile = NULL;
490 }
491
492 /* Return the current Objfile, or None if there isn't one. */
493
494 static PyObject *
495 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
496 {
497 PyObject *result;
498
499 if (! gdbpy_current_objfile)
500 Py_RETURN_NONE;
501
502 result = objfile_to_objfile_object (gdbpy_current_objfile);
503 if (result)
504 Py_INCREF (result);
505 return result;
506 }
507
508 /* Return a sequence holding all the Objfiles. */
509
510 static PyObject *
511 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
512 {
513 struct objfile *objf;
514 PyObject *list;
515
516 list = PyList_New (0);
517 if (!list)
518 return NULL;
519
520 ALL_OBJFILES (objf)
521 {
522 PyObject *item = objfile_to_objfile_object (objf);
523
524 if (!item || PyList_Append (list, item) == -1)
525 {
526 Py_DECREF (list);
527 return NULL;
528 }
529 }
530
531 return list;
532 }
533
534 #else /* HAVE_PYTHON */
535
536 /* Dummy implementation of the gdb "python" command. */
537
538 static void
539 python_command (char *arg, int from_tty)
540 {
541 while (arg && *arg && isspace (*arg))
542 ++arg;
543 if (arg && *arg)
544 error (_("Python scripting is not supported in this copy of GDB."));
545 else
546 {
547 struct command_line *l = get_command_line (python_control, "");
548 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
549
550 execute_control_command_untraced (l);
551 do_cleanups (cleanups);
552 }
553 }
554
555 void
556 eval_python_from_control_command (struct command_line *cmd)
557 {
558 error (_("Python scripting is not supported in this copy of GDB."));
559 }
560
561 void
562 source_python_script (FILE *stream, const char *file)
563 {
564 throw_error (UNSUPPORTED_ERROR,
565 _("Python scripting is not supported in this copy of GDB."));
566 }
567
568 #endif /* HAVE_PYTHON */
569
570 \f
571
572 /* Lists for 'maint set python' commands. */
573
574 struct cmd_list_element *set_python_list;
575 struct cmd_list_element *show_python_list;
576
577 /* Function for use by 'maint set python' prefix command. */
578
579 static void
580 set_python (char *args, int from_tty)
581 {
582 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
583 }
584
585 /* Function for use by 'maint show python' prefix command. */
586
587 static void
588 show_python (char *args, int from_tty)
589 {
590 cmd_show_list (show_python_list, from_tty, "");
591 }
592
593 /* Initialize the Python code. */
594
595 /* Provide a prototype to silence -Wmissing-prototypes. */
596 extern initialize_file_ftype _initialize_python;
597
598 void
599 _initialize_python (void)
600 {
601 add_com ("python", class_obscure, python_command,
602 #ifdef HAVE_PYTHON
603 _("\
604 Evaluate a Python command.\n\
605 \n\
606 The command can be given as an argument, for instance:\n\
607 \n\
608 python print 23\n\
609 \n\
610 If no argument is given, the following lines are read and used\n\
611 as the Python commands. Type a line containing \"end\" to indicate\n\
612 the end of the command.")
613 #else /* HAVE_PYTHON */
614 _("\
615 Evaluate a Python command.\n\
616 \n\
617 Python scripting is not supported in this copy of GDB.\n\
618 This command is only a placeholder.")
619 #endif /* HAVE_PYTHON */
620 );
621
622 add_prefix_cmd ("python", no_class, show_python,
623 _("Prefix command for python maintenance settings."),
624 &show_python_list, "maintenance show python ", 0,
625 &maintenance_show_cmdlist);
626 add_prefix_cmd ("python", no_class, set_python,
627 _("Prefix command for python maintenance settings."),
628 &set_python_list, "maintenance set python ", 0,
629 &maintenance_set_cmdlist);
630
631 add_setshow_boolean_cmd ("print-stack", class_maintenance,
632 &gdbpy_should_print_stack, _("\
633 Enable or disable printing of Python stack dump on error."), _("\
634 Show whether Python stack will be printed on error."), _("\
635 Enables or disables printing of Python stack traces."),
636 NULL, NULL,
637 &set_python_list,
638 &show_python_list);
639
640 #ifdef HAVE_PYTHON
641 Py_Initialize ();
642 PyEval_InitThreads ();
643
644 gdb_module = Py_InitModule ("gdb", GdbMethods);
645
646 /* The casts to (char*) are for python 2.4. */
647 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
648 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
649 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
650
651 gdbpy_initialize_auto_load ();
652 gdbpy_initialize_values ();
653 gdbpy_initialize_frames ();
654 gdbpy_initialize_commands ();
655 gdbpy_initialize_symbols ();
656 gdbpy_initialize_symtabs ();
657 gdbpy_initialize_blocks ();
658 gdbpy_initialize_functions ();
659 gdbpy_initialize_parameters ();
660 gdbpy_initialize_types ();
661 gdbpy_initialize_pspace ();
662 gdbpy_initialize_objfile ();
663 gdbpy_initialize_breakpoints ();
664 gdbpy_initialize_lazy_string ();
665
666 PyRun_SimpleString ("import gdb");
667 PyRun_SimpleString ("gdb.pretty_printers = []");
668
669 gdbpy_to_string_cst = PyString_FromString ("to_string");
670 gdbpy_children_cst = PyString_FromString ("children");
671 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
672 gdbpy_doc_cst = PyString_FromString ("__doc__");
673
674 /* Create a couple objects which are used for Python's stdout and
675 stderr. */
676 PyRun_SimpleString ("\
677 import sys\n\
678 class GdbOutputFile:\n\
679 def close(self):\n\
680 # Do nothing.\n\
681 return None\n\
682 \n\
683 def isatty(self):\n\
684 return False\n\
685 \n\
686 def write(self, s):\n\
687 gdb.write(s)\n\
688 \n\
689 def writelines(self, iterable):\n\
690 for line in iterable:\n\
691 self.write(line)\n\
692 \n\
693 def flush(self):\n\
694 gdb.flush()\n\
695 \n\
696 sys.stderr = GdbOutputFile()\n\
697 sys.stdout = GdbOutputFile()\n\
698 ");
699
700 /* Release the GIL while gdb runs. */
701 PyThreadState_Swap (NULL);
702 PyEval_ReleaseLock ();
703
704 #endif /* HAVE_PYTHON */
705 }
706
707 \f
708
709 #if HAVE_PYTHON
710
711 static PyMethodDef GdbMethods[] =
712 {
713 { "history", gdbpy_history, METH_VARARGS,
714 "Get a value from history" },
715 { "execute", execute_gdb_command, METH_VARARGS,
716 "Execute a gdb command" },
717 { "parameter", gdbpy_parameter, METH_VARARGS,
718 "Return a gdb parameter's value" },
719
720 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
721 "Return a tuple of all breakpoint objects" },
722
723 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
724 "Find the default visualizer for a Value." },
725
726 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
727 "Return the current Progspace." },
728 { "progspaces", gdbpy_progspaces, METH_NOARGS,
729 "Return a sequence of all progspaces." },
730
731 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
732 "Return the current Objfile being loaded, or None." },
733 { "objfiles", gdbpy_objfiles, METH_NOARGS,
734 "Return a sequence of all loaded objfiles." },
735
736 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
737 "selected_frame () -> gdb.Frame.\n\
738 Return the selected frame object." },
739 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
740 "stop_reason_string (Integer) -> String.\n\
741 Return a string explaining unwind stop reason." },
742
743 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
744 METH_VARARGS | METH_KEYWORDS,
745 "lookup_type (name [, block]) -> type\n\
746 Return a Type corresponding to the given name." },
747 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
748 METH_VARARGS | METH_KEYWORDS,
749 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
750 Return a tuple with the symbol corresponding to the given name (or None) and\n\
751 a boolean indicating if name is a field of the current implied argument\n\
752 `this' (when the current language is object-oriented)." },
753 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
754 "Return the block containing the given pc value, or None." },
755 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
756 "parse_and_eval (String) -> Value.\n\
757 Parse String as an expression, evaluate it, and return the result as a Value."
758 },
759
760 { "target_charset", gdbpy_target_charset, METH_NOARGS,
761 "target_charset () -> string.\n\
762 Return the name of the current target charset." },
763 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
764 "target_wide_charset () -> string.\n\
765 Return the name of the current target wide charset." },
766
767 { "write", gdbpy_write, METH_VARARGS,
768 "Write a string using gdb's filtered stream." },
769 { "flush", gdbpy_flush, METH_NOARGS,
770 "Flush gdb's filtered stdout stream." },
771
772 {NULL, NULL, 0, NULL}
773 };
774
775 #endif /* HAVE_PYTHON */