gdb/testsuite/
[deliverable/binutils-gdb.git] / gdb / python / python.c
CommitLineData
d57a3c85
TJB
1/* General python/gdb code
2
0fb0cc75 3 Copyright (C) 2008, 2009 Free Software Foundation, Inc.
d57a3c85
TJB
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"
d452c4bc 21#include "arch-utils.h"
d57a3c85
TJB
22#include "command.h"
23#include "ui-out.h"
24#include "cli/cli-script.h"
25#include "gdbcmd.h"
89c73ade
TT
26#include "objfiles.h"
27#include "observer.h"
d452c4bc
UW
28#include "value.h"
29#include "language.h"
d57a3c85
TJB
30
31#include <ctype.h>
32
33/* True if we should print the stack when catching a Python error,
34 false otherwise. */
35static int gdbpy_should_print_stack = 1;
36
89c73ade
TT
37/* This is true if we should auto-load python code when an objfile is
38 opened, false otherwise. */
39static int gdbpy_auto_load = 1;
40
d57a3c85
TJB
41#ifdef HAVE_PYTHON
42
43#include "python.h"
44#include "libiberty.h"
45#include "cli/cli-decode.h"
46#include "charset.h"
47#include "top.h"
48#include "exceptions.h"
49#include "python-internal.h"
50#include "version.h"
51#include "target.h"
52#include "gdbthread.h"
53
12453b93 54static PyMethodDef GdbMethods[];
d57a3c85
TJB
55
56PyObject *gdb_module;
57
a6bac58e
TT
58/* Some string constants we may wish to use. */
59PyObject *gdbpy_to_string_cst;
60PyObject *gdbpy_children_cst;
61PyObject *gdbpy_display_hint_cst;
d8906c6f
TJB
62PyObject *gdbpy_doc_cst;
63
d452c4bc
UW
64
65/* Architecture and language to be used in callbacks from
66 the Python interpreter. */
67struct gdbarch *python_gdbarch;
68const struct language_defn *python_language;
69
70/* Restore global language and architecture and Python GIL state
71 when leaving the Python interpreter. */
72
73struct python_env
74{
75 PyGILState_STATE state;
76 struct gdbarch *gdbarch;
77 const struct language_defn *language;
78};
79
80static void
81restore_python_env (void *p)
82{
83 struct python_env *env = (struct python_env *)p;
84 PyGILState_Release (env->state);
85 python_gdbarch = env->gdbarch;
86 python_language = env->language;
87 xfree (env);
88}
89
90/* Called before entering the Python interpreter to install the
91 current language and architecture to be used for Python values. */
92
93struct cleanup *
94ensure_python_env (struct gdbarch *gdbarch,
95 const struct language_defn *language)
96{
97 struct python_env *env = xmalloc (sizeof *env);
98
99 env->state = PyGILState_Ensure ();
100 env->gdbarch = python_gdbarch;
101 env->language = python_language;
102
103 python_gdbarch = gdbarch;
104 python_language = language;
105
106 return make_cleanup (restore_python_env, env);
107}
108
109
d57a3c85
TJB
110/* Given a command_line, return a command string suitable for passing
111 to Python. Lines in the string are separated by newlines. The
112 return value is allocated using xmalloc and the caller is
113 responsible for freeing it. */
114
115static char *
116compute_python_string (struct command_line *l)
117{
118 struct command_line *iter;
119 char *script = NULL;
120 int size = 0;
121 int here;
122
123 for (iter = l; iter; iter = iter->next)
124 size += strlen (iter->line) + 1;
125
126 script = xmalloc (size + 1);
127 here = 0;
128 for (iter = l; iter; iter = iter->next)
129 {
130 int len = strlen (iter->line);
131 strcpy (&script[here], iter->line);
132 here += len;
133 script[here++] = '\n';
134 }
135 script[here] = '\0';
136 return script;
137}
138
139/* Take a command line structure representing a 'python' command, and
140 evaluate its body using the Python interpreter. */
141
142void
143eval_python_from_control_command (struct command_line *cmd)
144{
12453b93 145 int ret;
d57a3c85 146 char *script;
ca30a762 147 struct cleanup *cleanup;
d57a3c85
TJB
148
149 if (cmd->body_count != 1)
150 error (_("Invalid \"python\" block structure."));
151
d452c4bc 152 cleanup = ensure_python_env (get_current_arch (), current_language);
ca30a762 153
d57a3c85 154 script = compute_python_string (cmd->body_list[0]);
12453b93 155 ret = PyRun_SimpleString (script);
d57a3c85 156 xfree (script);
12453b93 157 if (ret)
d57a3c85
TJB
158 {
159 gdbpy_print_stack ();
12453b93 160 error (_("Error while executing Python code."));
d57a3c85 161 }
ca30a762
TT
162
163 do_cleanups (cleanup);
d57a3c85
TJB
164}
165
166/* Implementation of the gdb "python" command. */
167
168static void
169python_command (char *arg, int from_tty)
170{
ca30a762 171 struct cleanup *cleanup;
d452c4bc 172 cleanup = ensure_python_env (get_current_arch (), current_language);
ca30a762 173
d57a3c85
TJB
174 while (arg && *arg && isspace (*arg))
175 ++arg;
176 if (arg && *arg)
177 {
12453b93 178 if (PyRun_SimpleString (arg))
d57a3c85
TJB
179 {
180 gdbpy_print_stack ();
12453b93 181 error (_("Error while executing Python code."));
d57a3c85
TJB
182 }
183 }
184 else
185 {
186 struct command_line *l = get_command_line (python_control, "");
ca30a762 187 make_cleanup_free_command_lines (&l);
d57a3c85 188 execute_control_command_untraced (l);
d57a3c85 189 }
ca30a762
TT
190
191 do_cleanups (cleanup);
d57a3c85
TJB
192}
193
194\f
195
196/* Transform a gdb parameters's value into a Python value. May return
197 NULL (and set a Python exception) on error. Helper function for
198 get_parameter. */
199
200static PyObject *
201parameter_to_python (struct cmd_list_element *cmd)
202{
203 switch (cmd->var_type)
204 {
205 case var_string:
206 case var_string_noescape:
207 case var_optional_filename:
208 case var_filename:
209 case var_enum:
210 {
211 char *str = * (char **) cmd->var;
212 if (! str)
213 str = "";
214 return PyString_Decode (str, strlen (str), host_charset (), NULL);
215 }
216
217 case var_boolean:
218 {
219 if (* (int *) cmd->var)
220 Py_RETURN_TRUE;
221 else
222 Py_RETURN_FALSE;
223 }
224
225 case var_auto_boolean:
226 {
227 enum auto_boolean ab = * (enum auto_boolean *) cmd->var;
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 *) cmd->var) == INT_MAX)
238 Py_RETURN_NONE;
239 /* Fall through. */
240 case var_zinteger:
241 return PyLong_FromLong (* (int *) cmd->var);
242
243 case var_uinteger:
244 {
245 unsigned int val = * (unsigned int *) cmd->var;
246 if (val == UINT_MAX)
247 Py_RETURN_NONE;
248 return PyLong_FromUnsignedLong (val);
249 }
250 }
251
252 return PyErr_Format (PyExc_RuntimeError, "programmer error: unhandled type");
253}
254
255/* A Python function which returns a gdb parameter's value as a Python
256 value. */
257
258static PyObject *
8f500870 259gdbpy_parameter (PyObject *self, PyObject *args)
d57a3c85
TJB
260{
261 struct cmd_list_element *alias, *prefix, *cmd;
262 char *arg, *newarg;
cc924cad 263 int found = -1;
d57a3c85
TJB
264 volatile struct gdb_exception except;
265
266 if (! PyArg_ParseTuple (args, "s", &arg))
267 return NULL;
268
269 newarg = concat ("show ", arg, (char *) NULL);
270
271 TRY_CATCH (except, RETURN_MASK_ALL)
272 {
cc924cad 273 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
d57a3c85
TJB
274 }
275 xfree (newarg);
276 GDB_PY_HANDLE_EXCEPTION (except);
cc924cad
TJB
277 if (!found)
278 return PyErr_Format (PyExc_RuntimeError,
279 "could not find parameter `%s'", arg);
d57a3c85
TJB
280
281 if (! cmd->var)
8f500870 282 return PyErr_Format (PyExc_RuntimeError, "`%s' is not a parameter", arg);
d57a3c85
TJB
283 return parameter_to_python (cmd);
284}
285
286/* A Python function which evaluates a string using the gdb CLI. */
287
288static PyObject *
289execute_gdb_command (PyObject *self, PyObject *args)
290{
291 struct cmd_list_element *alias, *prefix, *cmd;
292 char *arg, *newarg;
12453b93
TJB
293 PyObject *from_tty_obj = NULL;
294 int from_tty;
295 int cmp;
d57a3c85 296 volatile struct gdb_exception except;
d57a3c85 297
12453b93 298 if (! PyArg_ParseTuple (args, "s|O!", &arg, &PyBool_Type, &from_tty_obj))
d57a3c85
TJB
299 return NULL;
300
12453b93
TJB
301 from_tty = 0;
302 if (from_tty_obj)
303 {
304 cmp = PyObject_IsTrue (from_tty_obj);
305 if (cmp < 0)
306 return NULL;
307 from_tty = cmp;
308 }
309
d57a3c85
TJB
310 TRY_CATCH (except, RETURN_MASK_ALL)
311 {
86c6265d
TT
312 /* Copy the argument text in case the command modifies it. */
313 char *copy = xstrdup (arg);
314 struct cleanup *cleanup = make_cleanup (xfree, copy);
315 execute_command (copy, from_tty);
316 do_cleanups (cleanup);
d57a3c85
TJB
317 }
318 GDB_PY_HANDLE_EXCEPTION (except);
319
347bddb7
PA
320 /* Do any commands attached to breakpoint we stopped at. */
321 bpstat_do_actions ();
d57a3c85
TJB
322
323 Py_RETURN_NONE;
324}
325
326\f
327
328/* Printing. */
329
330/* A python function to write a single string using gdb's filtered
331 output stream. */
332static PyObject *
333gdbpy_write (PyObject *self, PyObject *args)
334{
335 char *arg;
336 if (! PyArg_ParseTuple (args, "s", &arg))
337 return NULL;
338 printf_filtered ("%s", arg);
339 Py_RETURN_NONE;
340}
341
342/* A python function to flush gdb's filtered output stream. */
343static PyObject *
344gdbpy_flush (PyObject *self, PyObject *args)
345{
346 gdb_flush (gdb_stdout);
347 Py_RETURN_NONE;
348}
349
350/* Print a python exception trace, or print nothing and clear the
351 python exception, depending on gdbpy_should_print_stack. Only call
352 this if a python exception is set. */
353void
354gdbpy_print_stack (void)
355{
356 if (gdbpy_should_print_stack)
357 PyErr_Print ();
358 else
359 PyErr_Clear ();
360}
361
89c73ade
TT
362\f
363
364/* The "current" objfile. This is set when gdb detects that a new
365 objfile has been loaded. It is only set for the duration of a call
366 to gdbpy_new_objfile; it is NULL at other times. */
367static struct objfile *gdbpy_current_objfile;
368
369/* The file name we attempt to read. */
370#define GDBPY_AUTO_FILENAME "-gdb.py"
371
372/* This is a new_objfile observer callback which loads python code
373 based on the path to the objfile. */
374static void
375gdbpy_new_objfile (struct objfile *objfile)
376{
377 char *realname;
378 char *filename, *debugfile;
379 int len;
380 FILE *input;
89c73ade
TT
381 struct cleanup *cleanups;
382
383 if (!gdbpy_auto_load || !objfile || !objfile->name)
384 return;
385
d452c4bc 386 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
89c73ade
TT
387
388 gdbpy_current_objfile = objfile;
389
390 realname = gdb_realpath (objfile->name);
391 len = strlen (realname);
392 filename = xmalloc (len + sizeof (GDBPY_AUTO_FILENAME));
393 memcpy (filename, realname, len);
394 strcpy (filename + len, GDBPY_AUTO_FILENAME);
395
396 input = fopen (filename, "r");
397 debugfile = filename;
398
d452c4bc 399 make_cleanup (xfree, filename);
89c73ade
TT
400 make_cleanup (xfree, realname);
401
402 if (!input && debug_file_directory)
403 {
404 /* Also try the same file in the separate debug info directory. */
405 debugfile = xmalloc (strlen (filename)
406 + strlen (debug_file_directory) + 1);
407 strcpy (debugfile, debug_file_directory);
408 /* FILENAME is absolute, so we don't need a "/" here. */
409 strcat (debugfile, filename);
410
411 make_cleanup (xfree, debugfile);
412 input = fopen (debugfile, "r");
413 }
414
415 if (!input && gdb_datadir)
416 {
417 /* Also try the same file in a subdirectory of gdb's data
418 directory. */
419 debugfile = xmalloc (strlen (gdb_datadir) + strlen (filename)
420 + strlen ("/auto-load") + 1);
421 strcpy (debugfile, gdb_datadir);
422 strcat (debugfile, "/auto-load");
423 /* FILENAME is absolute, so we don't need a "/" here. */
424 strcat (debugfile, filename);
425
426 make_cleanup (xfree, debugfile);
427 input = fopen (debugfile, "r");
428 }
429
430 if (input)
431 {
432 /* We don't want to throw an exception here -- but the user
433 would like to know that something went wrong. */
434 if (PyRun_SimpleFile (input, debugfile))
435 gdbpy_print_stack ();
436 fclose (input);
437 }
438
439 do_cleanups (cleanups);
440 gdbpy_current_objfile = NULL;
89c73ade
TT
441}
442
443/* Return the current Objfile, or None if there isn't one. */
444static PyObject *
445gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
446{
447 PyObject *result;
448
449 if (! gdbpy_current_objfile)
450 Py_RETURN_NONE;
451
452 result = objfile_to_objfile_object (gdbpy_current_objfile);
453 if (result)
454 Py_INCREF (result);
455 return result;
456}
457
458/* Return a sequence holding all the Objfiles. */
459static PyObject *
460gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
461{
462 struct objfile *objf;
463 PyObject *list;
464
465 list = PyList_New (0);
466 if (!list)
467 return NULL;
468
469 ALL_OBJFILES (objf)
470 {
471 PyObject *item = objfile_to_objfile_object (objf);
472 if (!item || PyList_Append (list, item) == -1)
473 {
474 Py_DECREF (list);
475 return NULL;
476 }
477 }
478
479 return list;
480}
481
d57a3c85
TJB
482#else /* HAVE_PYTHON */
483
484/* Dummy implementation of the gdb "python" command. */
485
486static void
487python_command (char *arg, int from_tty)
488{
489 while (arg && *arg && isspace (*arg))
490 ++arg;
491 if (arg && *arg)
492 error (_("Python scripting is not supported in this copy of GDB."));
493 else
494 {
495 struct command_line *l = get_command_line (python_control, "");
496 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
497 execute_control_command_untraced (l);
498 do_cleanups (cleanups);
499 }
500}
501
502void
503eval_python_from_control_command (struct command_line *cmd)
504{
505 error (_("Python scripting is not supported in this copy of GDB."));
506}
507
508#endif /* HAVE_PYTHON */
509
510\f
511
512/* Lists for 'maint set python' commands. */
513
514static struct cmd_list_element *set_python_list;
515static struct cmd_list_element *show_python_list;
516
517/* Function for use by 'maint set python' prefix command. */
518
519static void
520set_python (char *args, int from_tty)
521{
522 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
523}
524
525/* Function for use by 'maint show python' prefix command. */
526
527static void
528show_python (char *args, int from_tty)
529{
530 cmd_show_list (show_python_list, from_tty, "");
531}
532
533/* Initialize the Python code. */
534
2c0b251b
PA
535/* Provide a prototype to silence -Wmissing-prototypes. */
536extern initialize_file_ftype _initialize_python;
537
d57a3c85
TJB
538void
539_initialize_python (void)
540{
541 add_com ("python", class_obscure, python_command,
542#ifdef HAVE_PYTHON
543 _("\
544Evaluate a Python command.\n\
545\n\
546The command can be given as an argument, for instance:\n\
547\n\
548 python print 23\n\
549\n\
550If no argument is given, the following lines are read and used\n\
551as the Python commands. Type a line containing \"end\" to indicate\n\
552the end of the command.")
553#else /* HAVE_PYTHON */
554 _("\
555Evaluate a Python command.\n\
556\n\
557Python scripting is not supported in this copy of GDB.\n\
558This command is only a placeholder.")
559#endif /* HAVE_PYTHON */
560 );
561
562 add_prefix_cmd ("python", no_class, show_python,
563 _("Prefix command for python maintenance settings."),
509238d6 564 &show_python_list, "maintenance show python ", 0,
d57a3c85
TJB
565 &maintenance_show_cmdlist);
566 add_prefix_cmd ("python", no_class, set_python,
567 _("Prefix command for python maintenance settings."),
509238d6 568 &set_python_list, "maintenance set python ", 0,
d57a3c85
TJB
569 &maintenance_set_cmdlist);
570
571 add_setshow_boolean_cmd ("print-stack", class_maintenance,
572 &gdbpy_should_print_stack, _("\
573Enable or disable printing of Python stack dump on error."), _("\
574Show whether Python stack will be printed on error."), _("\
575Enables or disables printing of Python stack traces."),
576 NULL, NULL,
577 &set_python_list,
578 &show_python_list);
579
89c73ade
TT
580 add_setshow_boolean_cmd ("auto-load", class_maintenance,
581 &gdbpy_auto_load, _("\
582Enable or disable auto-loading of Python code when an object is opened."), _("\
583Show whether Python code will be auto-loaded when an object is opened."), _("\
584Enables or disables auto-loading of Python code when an object is opened."),
585 NULL, NULL,
586 &set_python_list,
587 &show_python_list);
588
d57a3c85
TJB
589#ifdef HAVE_PYTHON
590 Py_Initialize ();
ca30a762 591 PyEval_InitThreads ();
d57a3c85
TJB
592
593 gdb_module = Py_InitModule ("gdb", GdbMethods);
594
595 /* The casts to (char*) are for python 2.4. */
596 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
597 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
598 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
599
a08702d6 600 gdbpy_initialize_values ();
f8f6f20b 601 gdbpy_initialize_frames ();
d8906c6f 602 gdbpy_initialize_commands ();
bc3b79fd 603 gdbpy_initialize_functions ();
2c74e833 604 gdbpy_initialize_types ();
89c73ade 605 gdbpy_initialize_objfile ();
a08702d6 606
d57a3c85 607 PyRun_SimpleString ("import gdb");
a6bac58e 608 PyRun_SimpleString ("gdb.pretty_printers = []");
d57a3c85 609
89c73ade
TT
610 observer_attach_new_objfile (gdbpy_new_objfile);
611
a6bac58e
TT
612 gdbpy_to_string_cst = PyString_FromString ("to_string");
613 gdbpy_children_cst = PyString_FromString ("children");
614 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
d8906c6f
TJB
615 gdbpy_doc_cst = PyString_FromString ("__doc__");
616
d57a3c85
TJB
617 /* Create a couple objects which are used for Python's stdout and
618 stderr. */
619 PyRun_SimpleString ("\
620import sys\n\
621class GdbOutputFile:\n\
622 def close(self):\n\
623 # Do nothing.\n\
624 return None\n\
625\n\
626 def isatty(self):\n\
627 return False\n\
628\n\
629 def write(self, s):\n\
630 gdb.write(s)\n\
631\n\
632 def writelines(self, iterable):\n\
633 for line in iterable:\n\
634 self.write(line)\n\
635\n\
636 def flush(self):\n\
637 gdb.flush()\n\
638\n\
639sys.stderr = GdbOutputFile()\n\
640sys.stdout = GdbOutputFile()\n\
641");
ca30a762
TT
642
643 /* Release the GIL while gdb runs. */
644 PyThreadState_Swap (NULL);
645 PyEval_ReleaseLock ();
646
d57a3c85
TJB
647#endif /* HAVE_PYTHON */
648}
12453b93
TJB
649
650\f
651
652#if HAVE_PYTHON
653
654static PyMethodDef GdbMethods[] =
655{
656 { "history", gdbpy_history, METH_VARARGS,
657 "Get a value from history" },
658 { "execute", execute_gdb_command, METH_VARARGS,
659 "Execute a gdb command" },
8f500870 660 { "parameter", gdbpy_parameter, METH_VARARGS,
12453b93
TJB
661 "Return a gdb parameter's value" },
662
b6313243
TT
663 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
664 "Find the default visualizer for a Value." },
665
89c73ade
TT
666 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
667 "Return the current Objfile being loaded, or None." },
668 { "objfiles", gdbpy_objfiles, METH_NOARGS,
669 "Return a sequence of all loaded objfiles." },
670
f8f6f20b
TJB
671 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
672 "selected_frame () -> gdb.Frame.\n\
673Return the selected frame object." },
674 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
675 "stop_reason_string (Integer) -> String.\n\
676Return a string explaining unwind stop reason." },
677
2c74e833
TT
678 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
679 METH_VARARGS | METH_KEYWORDS,
680 "lookup_type (name [, block]) -> type\n\
681Return a Type corresponding to the given name." },
682
12453b93
TJB
683 { "write", gdbpy_write, METH_VARARGS,
684 "Write a string using gdb's filtered stream." },
685 { "flush", gdbpy_flush, METH_NOARGS,
686 "Flush gdb's filtered stdout stream." },
687
688 {NULL, NULL, 0, NULL}
689};
690
691#endif /* HAVE_PYTHON */
This page took 0.234762 seconds and 4 git commands to generate.