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