* python.c (gdbpy_print_stack): Ensure output ends with a newline.
[external/binutils.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   /* Note: If an exception occurs python will print the traceback and
381      clear the error indicator.  */
382   PyRun_SimpleFile (stream, file);
383
384   do_cleanups (cleanup);
385 }
386
387 \f
388
389 /* Printing.  */
390
391 /* A python function to write a single string using gdb's filtered
392    output stream.  */
393 static PyObject *
394 gdbpy_write (PyObject *self, PyObject *args)
395 {
396   char *arg;
397
398   if (! PyArg_ParseTuple (args, "s", &arg))
399     return NULL;
400   printf_filtered ("%s", arg);
401   Py_RETURN_NONE;
402 }
403
404 /* A python function to flush gdb's filtered output stream.  */
405 static PyObject *
406 gdbpy_flush (PyObject *self, PyObject *args)
407 {
408   gdb_flush (gdb_stdout);
409   Py_RETURN_NONE;
410 }
411
412 /* Print a python exception trace, or print nothing and clear the
413    python exception, depending on gdbpy_should_print_stack.  Only call
414    this if a python exception is set.  */
415 void
416 gdbpy_print_stack (void)
417 {
418   if (gdbpy_should_print_stack)
419     {
420       PyErr_Print ();
421       /* PyErr_Print doesn't necessarily end output with a newline.
422          This works because Python's stdout/stderr is fed through
423          printf_filtered.  */
424       begin_line ();
425     }
426   else
427     PyErr_Clear ();
428 }
429
430 \f
431
432 /* Return the current Progspace.
433    There always is one.  */
434
435 static PyObject *
436 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
437 {
438   PyObject *result;
439
440   result = pspace_to_pspace_object (current_program_space);
441   if (result)
442     Py_INCREF (result);
443   return result;
444 }
445
446 /* Return a sequence holding all the Progspaces.  */
447
448 static PyObject *
449 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
450 {
451   struct program_space *ps;
452   PyObject *list;
453
454   list = PyList_New (0);
455   if (!list)
456     return NULL;
457
458   ALL_PSPACES (ps)
459   {
460     PyObject *item = pspace_to_pspace_object (ps);
461
462     if (!item || PyList_Append (list, item) == -1)
463       {
464         Py_DECREF (list);
465         return NULL;
466       }
467   }
468
469   return list;
470 }
471
472 \f
473
474 /* The "current" objfile.  This is set when gdb detects that a new
475    objfile has been loaded.  It is only set for the duration of a call to
476    source_python_script_for_objfile; it is NULL at other times.  */
477 static struct objfile *gdbpy_current_objfile;
478
479 /* Set the current objfile to OBJFILE and then read STREAM,FILE as
480    Python code.  */
481
482 void
483 source_python_script_for_objfile (struct objfile *objfile,
484                                   FILE *stream, const char *file)
485 {
486   struct cleanup *cleanups;
487
488   cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
489   gdbpy_current_objfile = objfile;
490
491   /* Note: If an exception occurs python will print the traceback and
492      clear the error indicator.  */
493   PyRun_SimpleFile (stream, file);
494
495   do_cleanups (cleanups);
496   gdbpy_current_objfile = NULL;
497 }
498
499 /* Return the current Objfile, or None if there isn't one.  */
500
501 static PyObject *
502 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
503 {
504   PyObject *result;
505
506   if (! gdbpy_current_objfile)
507     Py_RETURN_NONE;
508
509   result = objfile_to_objfile_object (gdbpy_current_objfile);
510   if (result)
511     Py_INCREF (result);
512   return result;
513 }
514
515 /* Return a sequence holding all the Objfiles.  */
516
517 static PyObject *
518 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
519 {
520   struct objfile *objf;
521   PyObject *list;
522
523   list = PyList_New (0);
524   if (!list)
525     return NULL;
526
527   ALL_OBJFILES (objf)
528   {
529     PyObject *item = objfile_to_objfile_object (objf);
530
531     if (!item || PyList_Append (list, item) == -1)
532       {
533         Py_DECREF (list);
534         return NULL;
535       }
536   }
537
538   return list;
539 }
540
541 #else /* HAVE_PYTHON */
542
543 /* Dummy implementation of the gdb "python" command.  */
544
545 static void
546 python_command (char *arg, int from_tty)
547 {
548   while (arg && *arg && isspace (*arg))
549     ++arg;
550   if (arg && *arg)
551     error (_("Python scripting is not supported in this copy of GDB."));
552   else
553     {
554       struct command_line *l = get_command_line (python_control, "");
555       struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
556
557       execute_control_command_untraced (l);
558       do_cleanups (cleanups);
559     }
560 }
561
562 void
563 eval_python_from_control_command (struct command_line *cmd)
564 {
565   error (_("Python scripting is not supported in this copy of GDB."));
566 }
567
568 void
569 source_python_script (FILE *stream, const char *file)
570 {
571   throw_error (UNSUPPORTED_ERROR,
572                _("Python scripting is not supported in this copy of GDB."));
573 }
574
575 #endif /* HAVE_PYTHON */
576
577 \f
578
579 /* Lists for 'maint set python' commands.  */
580
581 struct cmd_list_element *set_python_list;
582 struct cmd_list_element *show_python_list;
583
584 /* Function for use by 'maint set python' prefix command.  */
585
586 static void
587 set_python (char *args, int from_tty)
588 {
589   help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
590 }
591
592 /* Function for use by 'maint show python' prefix command.  */
593
594 static void
595 show_python (char *args, int from_tty)
596 {
597   cmd_show_list (show_python_list, from_tty, "");
598 }
599
600 /* Initialize the Python code.  */
601
602 /* Provide a prototype to silence -Wmissing-prototypes.  */
603 extern initialize_file_ftype _initialize_python;
604
605 void
606 _initialize_python (void)
607 {
608   add_com ("python", class_obscure, python_command,
609 #ifdef HAVE_PYTHON
610            _("\
611 Evaluate a Python command.\n\
612 \n\
613 The command can be given as an argument, for instance:\n\
614 \n\
615     python print 23\n\
616 \n\
617 If no argument is given, the following lines are read and used\n\
618 as the Python commands.  Type a line containing \"end\" to indicate\n\
619 the end of the command.")
620 #else /* HAVE_PYTHON */
621            _("\
622 Evaluate a Python command.\n\
623 \n\
624 Python scripting is not supported in this copy of GDB.\n\
625 This command is only a placeholder.")
626 #endif /* HAVE_PYTHON */
627            );
628
629   add_prefix_cmd ("python", no_class, show_python,
630                   _("Prefix command for python maintenance settings."),
631                   &show_python_list, "maintenance show python ", 0,
632                   &maintenance_show_cmdlist);
633   add_prefix_cmd ("python", no_class, set_python,
634                   _("Prefix command for python maintenance settings."),
635                   &set_python_list, "maintenance set python ", 0,
636                   &maintenance_set_cmdlist);
637
638   add_setshow_boolean_cmd ("print-stack", class_maintenance,
639                            &gdbpy_should_print_stack, _("\
640 Enable or disable printing of Python stack dump on error."), _("\
641 Show whether Python stack will be printed on error."), _("\
642 Enables or disables printing of Python stack traces."),
643                            NULL, NULL,
644                            &set_python_list,
645                            &show_python_list);
646
647 #ifdef HAVE_PYTHON
648   Py_Initialize ();
649   PyEval_InitThreads ();
650
651   gdb_module = Py_InitModule ("gdb", GdbMethods);
652
653   /* The casts to (char*) are for python 2.4.  */
654   PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
655   PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
656   PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
657
658   gdbpy_initialize_auto_load ();
659   gdbpy_initialize_values ();
660   gdbpy_initialize_frames ();
661   gdbpy_initialize_commands ();
662   gdbpy_initialize_symbols ();
663   gdbpy_initialize_symtabs ();
664   gdbpy_initialize_blocks ();
665   gdbpy_initialize_functions ();
666   gdbpy_initialize_parameters ();
667   gdbpy_initialize_types ();
668   gdbpy_initialize_pspace ();
669   gdbpy_initialize_objfile ();
670   gdbpy_initialize_breakpoints ();
671   gdbpy_initialize_lazy_string ();
672
673   PyRun_SimpleString ("import gdb");
674   PyRun_SimpleString ("gdb.pretty_printers = []");
675
676   gdbpy_to_string_cst = PyString_FromString ("to_string");
677   gdbpy_children_cst = PyString_FromString ("children");
678   gdbpy_display_hint_cst = PyString_FromString ("display_hint");
679   gdbpy_doc_cst = PyString_FromString ("__doc__");
680
681   /* Create a couple objects which are used for Python's stdout and
682      stderr.  */
683   PyRun_SimpleString ("\
684 import sys\n\
685 class GdbOutputFile:\n\
686   def close(self):\n\
687     # Do nothing.\n\
688     return None\n\
689 \n\
690   def isatty(self):\n\
691     return False\n\
692 \n\
693   def write(self, s):\n\
694     gdb.write(s)\n\
695 \n\
696   def writelines(self, iterable):\n\
697     for line in iterable:\n\
698       self.write(line)\n\
699 \n\
700   def flush(self):\n\
701     gdb.flush()\n\
702 \n\
703 sys.stderr = GdbOutputFile()\n\
704 sys.stdout = GdbOutputFile()\n\
705 ");
706
707   /* Release the GIL while gdb runs.  */
708   PyThreadState_Swap (NULL);
709   PyEval_ReleaseLock ();
710
711 #endif /* HAVE_PYTHON */
712 }
713
714 \f
715
716 #if HAVE_PYTHON
717
718 static PyMethodDef GdbMethods[] =
719 {
720   { "history", gdbpy_history, METH_VARARGS,
721     "Get a value from history" },
722   { "execute", execute_gdb_command, METH_VARARGS,
723     "Execute a gdb command" },
724   { "parameter", gdbpy_parameter, METH_VARARGS,
725     "Return a gdb parameter's value" },
726
727   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
728     "Return a tuple of all breakpoint objects" },
729
730   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
731     "Find the default visualizer for a Value." },
732
733   { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
734     "Return the current Progspace." },
735   { "progspaces", gdbpy_progspaces, METH_NOARGS,
736     "Return a sequence of all progspaces." },
737
738   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
739     "Return the current Objfile being loaded, or None." },
740   { "objfiles", gdbpy_objfiles, METH_NOARGS,
741     "Return a sequence of all loaded objfiles." },
742
743   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
744     "selected_frame () -> gdb.Frame.\n\
745 Return the selected frame object." },
746   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
747     "stop_reason_string (Integer) -> String.\n\
748 Return a string explaining unwind stop reason." },
749
750   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
751     METH_VARARGS | METH_KEYWORDS,
752     "lookup_type (name [, block]) -> type\n\
753 Return a Type corresponding to the given name." },
754   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
755     METH_VARARGS | METH_KEYWORDS,
756     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
757 Return a tuple with the symbol corresponding to the given name (or None) and\n\
758 a boolean indicating if name is a field of the current implied argument\n\
759 `this' (when the current language is object-oriented)." },
760   { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
761     "Return the block containing the given pc value, or None." },
762   { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
763     "parse_and_eval (String) -> Value.\n\
764 Parse String as an expression, evaluate it, and return the result as a Value."
765   },
766
767   { "target_charset", gdbpy_target_charset, METH_NOARGS,
768     "target_charset () -> string.\n\
769 Return the name of the current target charset." },
770   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
771     "target_wide_charset () -> string.\n\
772 Return the name of the current target wide charset." },
773
774   { "write", gdbpy_write, METH_VARARGS,
775     "Write a string using gdb's filtered stream." },
776   { "flush", gdbpy_flush, METH_NOARGS,
777     "Flush gdb's filtered stdout stream." },
778
779   {NULL, NULL, 0, NULL}
780 };
781
782 #endif /* HAVE_PYTHON */