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