2011-11-28 Phil Muldoon <pmuldoon@redhat.com>
[external/binutils.git] / gdb / python / python.c
1 /* General python/gdb code
2
3    Copyright (C) 2008, 2009, 2010, 2011 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 #include "event-loop.h"
32 #include "serial.h"
33 #include "readline/tilde.h"
34 #include "python.h"
35
36 #include <ctype.h>
37
38 /* True if we should print the stack when catching a Python error,
39    false otherwise.  */
40 static int gdbpy_should_print_stack = 0;
41
42 #ifdef HAVE_PYTHON
43
44 #include "libiberty.h"
45 #include "cli/cli-decode.h"
46 #include "charset.h"
47 #include "top.h"
48 #include "solib.h"
49 #include "python-internal.h"
50 #include "linespec.h"
51 #include "source.h"
52 #include "version.h"
53 #include "target.h"
54 #include "gdbthread.h"
55 #include "observer.h"
56 #include "interps.h"
57
58 static PyMethodDef GdbMethods[];
59
60 PyObject *gdb_module;
61
62 /* Some string constants we may wish to use.  */
63 PyObject *gdbpy_to_string_cst;
64 PyObject *gdbpy_children_cst;
65 PyObject *gdbpy_display_hint_cst;
66 PyObject *gdbpy_doc_cst;
67 PyObject *gdbpy_enabled_cst;
68 PyObject *gdbpy_value_cst;
69
70 /* The GdbError exception.  */
71 PyObject *gdbpy_gdberror_exc;
72
73 /* The `gdb.error' base class.  */
74 PyObject *gdbpy_gdb_error;
75
76 /* The `gdb.MemoryError' exception.  */
77 PyObject *gdbpy_gdb_memory_error;
78
79 /* Architecture and language to be used in callbacks from
80    the Python interpreter.  */
81 struct gdbarch *python_gdbarch;
82 const struct language_defn *python_language;
83
84 /* Restore global language and architecture and Python GIL state
85    when leaving the Python interpreter.  */
86
87 struct python_env
88 {
89   PyGILState_STATE state;
90   struct gdbarch *gdbarch;
91   const struct language_defn *language;
92   PyObject *error_type, *error_value, *error_traceback;
93 };
94
95 static void
96 restore_python_env (void *p)
97 {
98   struct python_env *env = (struct python_env *)p;
99
100   /* Leftover Python error is forbidden by Python Exception Handling.  */
101   if (PyErr_Occurred ())
102     {
103       /* This order is similar to the one calling error afterwards. */
104       gdbpy_print_stack ();
105       warning (_("internal error: Unhandled Python exception"));
106     }
107
108   PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
109
110   PyGILState_Release (env->state);
111   python_gdbarch = env->gdbarch;
112   python_language = env->language;
113   xfree (env);
114 }
115
116 /* Called before entering the Python interpreter to install the
117    current language and architecture to be used for Python values.  */
118
119 struct cleanup *
120 ensure_python_env (struct gdbarch *gdbarch,
121                    const struct language_defn *language)
122 {
123   struct python_env *env = xmalloc (sizeof *env);
124
125   env->state = PyGILState_Ensure ();
126   env->gdbarch = python_gdbarch;
127   env->language = python_language;
128
129   python_gdbarch = gdbarch;
130   python_language = language;
131
132   /* Save it and ensure ! PyErr_Occurred () afterwards.  */
133   PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
134   
135   return make_cleanup (restore_python_env, env);
136 }
137
138 /* A wrapper around PyRun_SimpleFile.  FILENAME is the name of
139    the Python script to run.
140
141    One of the parameters of PyRun_SimpleFile is a FILE *.
142    The problem is that type FILE is extremely system and compiler
143    dependent.  So, unless the Python library has been compiled using
144    the same build environment as GDB, we run the risk of getting
145    a crash due to inconsistencies between the definition used by GDB,
146    and the definition used by Python.  A mismatch can very likely
147    lead to a crash.
148
149    There is also the situation where the Python library and GDB
150    are using two different versions of the C runtime library.
151    This is particularly visible on Windows, where few users would
152    build Python themselves (this is no trivial task on this platform),
153    and thus use binaries built by someone else instead. Python,
154    being built with VC, would use one version of the msvcr DLL
155    (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.  A FILE *
156    from one runtime does not necessarily operate correctly in
157    the other runtime.
158
159    To work around this potential issue, we create the FILE object
160    using Python routines, thus making sure that it is compatible
161    with the Python library.  */
162
163 static void
164 python_run_simple_file (const char *filename)
165 {
166   char *full_path;
167   PyObject *python_file;
168   struct cleanup *cleanup;
169
170   /* Because we have a string for a filename, and are using Python to
171      open the file, we need to expand any tilde in the path first.  */
172   full_path = tilde_expand (filename);
173   cleanup = make_cleanup (xfree, full_path);
174   python_file = PyFile_FromString (full_path, "r");
175   if (! python_file)
176     {
177       do_cleanups (cleanup);
178       gdbpy_print_stack ();
179       error (_("Error while opening file: %s"), full_path);
180     }
181  
182   make_cleanup_py_decref (python_file);
183   PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
184   do_cleanups (cleanup);
185 }
186
187 /* Given a command_line, return a command string suitable for passing
188    to Python.  Lines in the string are separated by newlines.  The
189    return value is allocated using xmalloc and the caller is
190    responsible for freeing it.  */
191
192 static char *
193 compute_python_string (struct command_line *l)
194 {
195   struct command_line *iter;
196   char *script = NULL;
197   int size = 0;
198   int here;
199
200   for (iter = l; iter; iter = iter->next)
201     size += strlen (iter->line) + 1;
202
203   script = xmalloc (size + 1);
204   here = 0;
205   for (iter = l; iter; iter = iter->next)
206     {
207       int len = strlen (iter->line);
208
209       strcpy (&script[here], iter->line);
210       here += len;
211       script[here++] = '\n';
212     }
213   script[here] = '\0';
214   return script;
215 }
216
217 /* Take a command line structure representing a 'python' command, and
218    evaluate its body using the Python interpreter.  */
219
220 void
221 eval_python_from_control_command (struct command_line *cmd)
222 {
223   int ret;
224   char *script;
225   struct cleanup *cleanup;
226
227   if (cmd->body_count != 1)
228     error (_("Invalid \"python\" block structure."));
229
230   cleanup = ensure_python_env (get_current_arch (), current_language);
231
232   script = compute_python_string (cmd->body_list[0]);
233   ret = PyRun_SimpleString (script);
234   xfree (script);
235   if (ret)
236     {
237       gdbpy_print_stack ();
238       error (_("Error while executing Python code."));
239     }
240
241   do_cleanups (cleanup);
242 }
243
244 /* Implementation of the gdb "python" command.  */
245
246 static void
247 python_command (char *arg, int from_tty)
248 {
249   struct cleanup *cleanup;
250
251   cleanup = ensure_python_env (get_current_arch (), current_language);
252
253   make_cleanup_restore_integer (&interpreter_async);
254   interpreter_async = 0;
255
256   while (arg && *arg && isspace (*arg))
257     ++arg;
258   if (arg && *arg)
259     {
260       if (PyRun_SimpleString (arg))
261         {
262           gdbpy_print_stack ();
263           error (_("Error while executing Python code."));
264         }
265     }
266   else
267     {
268       struct command_line *l = get_command_line (python_control, "");
269
270       make_cleanup_free_command_lines (&l);
271       execute_control_command_untraced (l);
272     }
273
274   do_cleanups (cleanup);
275 }
276
277 \f
278
279 /* Transform a gdb parameters's value into a Python value.  May return
280    NULL (and set a Python exception) on error.  Helper function for
281    get_parameter.  */
282 PyObject *
283 gdbpy_parameter_value (enum var_types type, void *var)
284 {
285   switch (type)
286     {
287     case var_string:
288     case var_string_noescape:
289     case var_optional_filename:
290     case var_filename:
291     case var_enum:
292       {
293         char *str = * (char **) var;
294
295         if (! str)
296           str = "";
297         return PyString_Decode (str, strlen (str), host_charset (), NULL);
298       }
299
300     case var_boolean:
301       {
302         if (* (int *) var)
303           Py_RETURN_TRUE;
304         else
305           Py_RETURN_FALSE;
306       }
307
308     case var_auto_boolean:
309       {
310         enum auto_boolean ab = * (enum auto_boolean *) var;
311
312         if (ab == AUTO_BOOLEAN_TRUE)
313           Py_RETURN_TRUE;
314         else if (ab == AUTO_BOOLEAN_FALSE)
315           Py_RETURN_FALSE;
316         else
317           Py_RETURN_NONE;
318       }
319
320     case var_integer:
321       if ((* (int *) var) == INT_MAX)
322         Py_RETURN_NONE;
323       /* Fall through.  */
324     case var_zinteger:
325       return PyLong_FromLong (* (int *) var);
326
327     case var_uinteger:
328       {
329         unsigned int val = * (unsigned int *) var;
330
331         if (val == UINT_MAX)
332           Py_RETURN_NONE;
333         return PyLong_FromUnsignedLong (val);
334       }
335     }
336
337   return PyErr_Format (PyExc_RuntimeError, 
338                        _("Programmer error: unhandled type."));
339 }
340
341 /* A Python function which returns a gdb parameter's value as a Python
342    value.  */
343
344 PyObject *
345 gdbpy_parameter (PyObject *self, PyObject *args)
346 {
347   struct cmd_list_element *alias, *prefix, *cmd;
348   const char *arg;
349   char *newarg;
350   int found = -1;
351   volatile struct gdb_exception except;
352
353   if (! PyArg_ParseTuple (args, "s", &arg))
354     return NULL;
355
356   newarg = concat ("show ", arg, (char *) NULL);
357
358   TRY_CATCH (except, RETURN_MASK_ALL)
359     {
360       found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
361     }
362   xfree (newarg);
363   GDB_PY_HANDLE_EXCEPTION (except);
364   if (!found)
365     return PyErr_Format (PyExc_RuntimeError,
366                          _("Could not find parameter `%s'."), arg);
367
368   if (! cmd->var)
369     return PyErr_Format (PyExc_RuntimeError, 
370                          _("`%s' is not a parameter."), arg);
371   return gdbpy_parameter_value (cmd->var_type, cmd->var);
372 }
373
374 /* Wrapper for target_charset.  */
375
376 static PyObject *
377 gdbpy_target_charset (PyObject *self, PyObject *args)
378 {
379   const char *cset = target_charset (python_gdbarch);
380
381   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
382 }
383
384 /* Wrapper for target_wide_charset.  */
385
386 static PyObject *
387 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
388 {
389   const char *cset = target_wide_charset (python_gdbarch);
390
391   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
392 }
393
394 /* A Python function which evaluates a string using the gdb CLI.  */
395
396 static PyObject *
397 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
398 {
399   const char *arg;
400   PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
401   int from_tty, to_string;
402   volatile struct gdb_exception except;
403   static char *keywords[] = {"command", "from_tty", "to_string", NULL };
404   char *result = NULL;
405
406   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
407                                      &PyBool_Type, &from_tty_obj,
408                                      &PyBool_Type, &to_string_obj))
409     return NULL;
410
411   from_tty = 0;
412   if (from_tty_obj)
413     {
414       int cmp = PyObject_IsTrue (from_tty_obj);
415       if (cmp < 0)
416         return NULL;
417       from_tty = cmp;
418     }
419
420   to_string = 0;
421   if (to_string_obj)
422     {
423       int cmp = PyObject_IsTrue (to_string_obj);
424       if (cmp < 0)
425         return NULL;
426       to_string = cmp;
427     }
428
429   TRY_CATCH (except, RETURN_MASK_ALL)
430     {
431       /* Copy the argument text in case the command modifies it.  */
432       char *copy = xstrdup (arg);
433       struct cleanup *cleanup = make_cleanup (xfree, copy);
434
435       make_cleanup_restore_integer (&interpreter_async);
436       interpreter_async = 0;
437
438       prevent_dont_repeat ();
439       if (to_string)
440         result = execute_command_to_string (copy, from_tty);
441       else
442         {
443           result = NULL;
444           execute_command (copy, from_tty);
445         }
446
447       do_cleanups (cleanup);
448     }
449   GDB_PY_HANDLE_EXCEPTION (except);
450
451   /* Do any commands attached to breakpoint we stopped at.  */
452   bpstat_do_actions ();
453
454   if (result)
455     {
456       PyObject *r = PyString_FromString (result);
457       xfree (result);
458       return r;
459     }
460   Py_RETURN_NONE;
461 }
462
463 /* Implementation of gdb.solib_name (Long) -> String.
464    Returns the name of the shared library holding a given address, or None.  */
465
466 static PyObject *
467 gdbpy_solib_name (PyObject *self, PyObject *args)
468 {
469   char *soname;
470   PyObject *str_obj;
471   gdb_py_longest pc;
472
473   if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
474     return NULL;
475
476   soname = solib_name_from_address (current_program_space, pc);
477   if (soname)
478     str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
479   else
480     {
481       str_obj = Py_None;
482       Py_INCREF (Py_None);
483     }
484
485   return str_obj;
486 }
487
488 /* A Python function which is a wrapper for decode_line_1.  */
489
490 static PyObject *
491 gdbpy_decode_line (PyObject *self, PyObject *args)
492 {
493   struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
494                                                   appease gcc.  */
495   struct symtab_and_line sal;
496   const char *arg = NULL;
497   char *copy = NULL;
498   struct cleanup *cleanups;
499   PyObject *result = NULL;
500   PyObject *return_result = NULL;
501   PyObject *unparsed = NULL;
502   volatile struct gdb_exception except;
503
504   if (! PyArg_ParseTuple (args, "|s", &arg))
505     return NULL;
506
507   cleanups = make_cleanup (null_cleanup, NULL);
508
509   TRY_CATCH (except, RETURN_MASK_ALL)
510     {
511       if (arg)
512         {
513           copy = xstrdup (arg);
514           make_cleanup (xfree, copy);
515           sals = decode_line_1 (&copy, 0, 0, 0, 0);
516           make_cleanup (xfree, sals.sals);
517         }
518       else
519         {
520           set_default_source_symtab_and_line ();
521           sal = get_current_source_symtab_and_line ();
522           sals.sals = &sal;
523           sals.nelts = 1;
524         }
525     }
526   if (except.reason < 0)
527     {
528       do_cleanups (cleanups);
529       /* We know this will always throw.  */
530       GDB_PY_HANDLE_EXCEPTION (except);
531     }
532
533   if (sals.nelts)
534     {
535       int i;
536
537       result = PyTuple_New (sals.nelts);
538       if (! result)
539         goto error;
540       for (i = 0; i < sals.nelts; ++i)
541         {
542           PyObject *obj;
543           char *str;
544
545           obj = symtab_and_line_to_sal_object (sals.sals[i]);
546           if (! obj)
547             {
548               Py_DECREF (result);
549               goto error;
550             }
551
552           PyTuple_SetItem (result, i, obj);
553         }
554     }
555   else
556     {
557       result = Py_None;
558       Py_INCREF (Py_None);
559     }
560
561   return_result = PyTuple_New (2);
562   if (! return_result)
563     {
564       Py_DECREF (result);
565       goto error;
566     }
567
568   if (copy && strlen (copy) > 0)
569     unparsed = PyString_FromString (copy);
570   else
571     {
572       unparsed = Py_None;
573       Py_INCREF (Py_None);
574     }
575
576   PyTuple_SetItem (return_result, 0, unparsed);
577   PyTuple_SetItem (return_result, 1, result);
578
579   do_cleanups (cleanups);
580
581   return return_result;
582
583  error:
584   do_cleanups (cleanups);
585   return NULL;
586 }
587
588 /* Parse a string and evaluate it as an expression.  */
589 static PyObject *
590 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
591 {
592   const char *expr_str;
593   struct value *result = NULL;
594   volatile struct gdb_exception except;
595
596   if (!PyArg_ParseTuple (args, "s", &expr_str))
597     return NULL;
598
599   TRY_CATCH (except, RETURN_MASK_ALL)
600     {
601       char *copy = xstrdup (expr_str);
602       struct cleanup *cleanup = make_cleanup (xfree, copy);
603
604       result = parse_and_eval (copy);
605       do_cleanups (cleanup);
606     }
607   GDB_PY_HANDLE_EXCEPTION (except);
608
609   return value_to_value_object (result);
610 }
611
612 /* Read a file as Python code.
613    FILE is the name of the file.
614    This does not throw any errors.  If an exception occurs python will print
615    the traceback and clear the error indicator.  */
616
617 void
618 source_python_script (const char *file)
619 {
620   struct cleanup *cleanup;
621
622   cleanup = ensure_python_env (get_current_arch (), current_language);
623   python_run_simple_file (file);
624   do_cleanups (cleanup);
625 }
626
627 \f
628
629 /* Posting and handling events.  */
630
631 /* A single event.  */
632 struct gdbpy_event
633 {
634   /* The Python event.  This is just a callable object.  */
635   PyObject *event;
636   /* The next event.  */
637   struct gdbpy_event *next;
638 };
639
640 /* All pending events.  */
641 static struct gdbpy_event *gdbpy_event_list;
642 /* The final link of the event list.  */
643 static struct gdbpy_event **gdbpy_event_list_end;
644
645 /* We use a file handler, and not an async handler, so that we can
646    wake up the main thread even when it is blocked in poll().  */
647 static struct serial *gdbpy_event_fds[2];
648
649 /* The file handler callback.  This reads from the internal pipe, and
650    then processes the Python event queue.  This will always be run in
651    the main gdb thread.  */
652
653 static void
654 gdbpy_run_events (struct serial *scb, void *context)
655 {
656   struct cleanup *cleanup;
657   int r;
658
659   cleanup = ensure_python_env (get_current_arch (), current_language);
660
661   /* Flush the fd.  Do this before flushing the events list, so that
662      any new event post afterwards is sure to re-awake the event
663      loop.  */
664   while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
665     ;
666
667   while (gdbpy_event_list)
668     {
669       /* Dispatching the event might push a new element onto the event
670          loop, so we update here "atomically enough".  */
671       struct gdbpy_event *item = gdbpy_event_list;
672       gdbpy_event_list = gdbpy_event_list->next;
673       if (gdbpy_event_list == NULL)
674         gdbpy_event_list_end = &gdbpy_event_list;
675
676       /* Ignore errors.  */
677       if (PyObject_CallObject (item->event, NULL) == NULL)
678         PyErr_Clear ();
679
680       Py_DECREF (item->event);
681       xfree (item);
682     }
683
684   do_cleanups (cleanup);
685 }
686
687 /* Submit an event to the gdb thread.  */
688 static PyObject *
689 gdbpy_post_event (PyObject *self, PyObject *args)
690 {
691   struct gdbpy_event *event;
692   PyObject *func;
693   int wakeup;
694
695   if (!PyArg_ParseTuple (args, "O", &func))
696     return NULL;
697
698   if (!PyCallable_Check (func))
699     {
700       PyErr_SetString (PyExc_RuntimeError, 
701                        _("Posted event is not callable"));
702       return NULL;
703     }
704
705   Py_INCREF (func);
706
707   /* From here until the end of the function, we have the GIL, so we
708      can operate on our global data structures without worrying.  */
709   wakeup = gdbpy_event_list == NULL;
710
711   event = XNEW (struct gdbpy_event);
712   event->event = func;
713   event->next = NULL;
714   *gdbpy_event_list_end = event;
715   gdbpy_event_list_end = &event->next;
716
717   /* Wake up gdb when needed.  */
718   if (wakeup)
719     {
720       char c = 'q';             /* Anything. */
721
722       if (serial_write (gdbpy_event_fds[1], &c, 1))
723         return PyErr_SetFromErrno (PyExc_IOError);
724     }
725
726   Py_RETURN_NONE;
727 }
728
729 /* Initialize the Python event handler.  */
730 static void
731 gdbpy_initialize_events (void)
732 {
733   if (serial_pipe (gdbpy_event_fds) == 0)
734     {
735       gdbpy_event_list_end = &gdbpy_event_list;
736       serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
737     }
738 }
739
740 \f
741
742 static void
743 before_prompt_hook (const char *current_gdb_prompt)
744 {
745   struct cleanup *cleanup;
746   char *prompt = NULL;
747
748   cleanup = ensure_python_env (get_current_arch (), current_language);
749
750   if (PyObject_HasAttrString (gdb_module, "prompt_hook"))
751     {
752       PyObject *hook;
753
754       hook = PyObject_GetAttrString (gdb_module, "prompt_hook");
755       if (hook == NULL)
756         goto fail;
757
758       if (PyCallable_Check (hook))
759         {
760           PyObject *result;
761           PyObject *current_prompt;
762
763           current_prompt = PyString_FromString (current_gdb_prompt);
764           if (current_prompt == NULL)
765             goto fail;
766
767           result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);
768
769           Py_DECREF (current_prompt);
770
771           if (result == NULL)
772             goto fail;
773
774           make_cleanup_py_decref (result);
775
776           /* Return type should be None, or a String.  If it is None,
777              fall through, we will not set a prompt.  If it is a
778              string, set  PROMPT.  Anything else, set an exception.  */
779           if (result != Py_None && ! PyString_Check (result))
780             {
781               PyErr_Format (PyExc_RuntimeError,
782                             _("Return from prompt_hook must " \
783                               "be either a Python string, or None"));
784               goto fail;
785             }
786
787           if (result != Py_None)
788             {
789               prompt = python_string_to_host_string (result);
790
791               if (prompt == NULL)
792                 goto fail;
793               else
794                 make_cleanup (xfree, prompt);
795             }
796         }
797     }
798
799   /* If a prompt has been set, PROMPT will not be NULL.  If it is
800      NULL, do not set the prompt.  */
801   if (prompt != NULL)
802     set_prompt (prompt);
803
804   do_cleanups (cleanup);
805   return;
806
807  fail:
808   gdbpy_print_stack ();
809   do_cleanups (cleanup);
810   return;
811 }
812
813 \f
814
815 /* Printing.  */
816
817 /* A python function to write a single string using gdb's filtered
818    output stream .  The optional keyword STREAM can be used to write
819    to a particular stream.  The default stream is to gdb_stdout.  */
820
821 static PyObject *
822 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
823 {
824   const char *arg;
825   static char *keywords[] = {"text", "stream", NULL };
826   int stream_type = 0;
827   
828   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
829                                      &stream_type))
830     return NULL;
831
832   switch (stream_type)
833     {
834     case 1:
835       {
836         fprintf_filtered (gdb_stderr, "%s", arg);
837         break;
838       }
839     case 2:
840       {
841         fprintf_filtered (gdb_stdlog, "%s", arg);
842         break;
843       }
844     default:
845       fprintf_filtered (gdb_stdout, "%s", arg);
846     }
847      
848   Py_RETURN_NONE;
849 }
850
851 /* A python function to flush a gdb stream.  The optional keyword
852    STREAM can be used to flush a particular stream.  The default stream
853    is gdb_stdout.  */
854
855 static PyObject *
856 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
857 {
858   static char *keywords[] = {"stream", NULL };
859   int stream_type = 0;
860   
861   if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
862                                      &stream_type))
863     return NULL;
864
865   switch (stream_type)
866     {
867     case 1:
868       {
869         gdb_flush (gdb_stderr);
870         break;
871       }
872     case 2:
873       {
874         gdb_flush (gdb_stdlog);
875         break;
876       }
877     default:
878       gdb_flush (gdb_stdout);
879     }
880      
881   Py_RETURN_NONE;
882 }
883
884 /* Print a python exception trace, or print nothing and clear the
885    python exception, depending on gdbpy_should_print_stack.  Only call
886    this if a python exception is set.  */
887 void
888 gdbpy_print_stack (void)
889 {
890   if (gdbpy_should_print_stack)
891     {
892       PyErr_Print ();
893       /* PyErr_Print doesn't necessarily end output with a newline.
894          This works because Python's stdout/stderr is fed through
895          printf_filtered.  */
896       begin_line ();
897     }
898   else
899     PyErr_Clear ();
900 }
901
902 \f
903
904 /* Return the current Progspace.
905    There always is one.  */
906
907 static PyObject *
908 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
909 {
910   PyObject *result;
911
912   result = pspace_to_pspace_object (current_program_space);
913   if (result)
914     Py_INCREF (result);
915   return result;
916 }
917
918 /* Return a sequence holding all the Progspaces.  */
919
920 static PyObject *
921 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
922 {
923   struct program_space *ps;
924   PyObject *list;
925
926   list = PyList_New (0);
927   if (!list)
928     return NULL;
929
930   ALL_PSPACES (ps)
931   {
932     PyObject *item = pspace_to_pspace_object (ps);
933
934     if (!item || PyList_Append (list, item) == -1)
935       {
936         Py_DECREF (list);
937         return NULL;
938       }
939   }
940
941   return list;
942 }
943
944 \f
945
946 /* The "current" objfile.  This is set when gdb detects that a new
947    objfile has been loaded.  It is only set for the duration of a call to
948    source_python_script_for_objfile; it is NULL at other times.  */
949 static struct objfile *gdbpy_current_objfile;
950
951 /* Set the current objfile to OBJFILE and then read FILE as Python code.
952    This does not throw any errors.  If an exception occurs python will print
953    the traceback and clear the error indicator.  */
954
955 void
956 source_python_script_for_objfile (struct objfile *objfile, const char *file)
957 {
958   struct cleanup *cleanups;
959
960   cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
961   gdbpy_current_objfile = objfile;
962
963   python_run_simple_file (file);
964
965   do_cleanups (cleanups);
966   gdbpy_current_objfile = NULL;
967 }
968
969 /* Return the current Objfile, or None if there isn't one.  */
970
971 static PyObject *
972 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
973 {
974   PyObject *result;
975
976   if (! gdbpy_current_objfile)
977     Py_RETURN_NONE;
978
979   result = objfile_to_objfile_object (gdbpy_current_objfile);
980   if (result)
981     Py_INCREF (result);
982   return result;
983 }
984
985 /* Return a sequence holding all the Objfiles.  */
986
987 static PyObject *
988 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
989 {
990   struct objfile *objf;
991   PyObject *list;
992
993   list = PyList_New (0);
994   if (!list)
995     return NULL;
996
997   ALL_OBJFILES (objf)
998   {
999     PyObject *item = objfile_to_objfile_object (objf);
1000
1001     if (!item || PyList_Append (list, item) == -1)
1002       {
1003         Py_DECREF (list);
1004         return NULL;
1005       }
1006   }
1007
1008   return list;
1009 }
1010
1011 #else /* HAVE_PYTHON */
1012
1013 /* Dummy implementation of the gdb "python" command.  */
1014
1015 static void
1016 python_command (char *arg, int from_tty)
1017 {
1018   while (arg && *arg && isspace (*arg))
1019     ++arg;
1020   if (arg && *arg)
1021     error (_("Python scripting is not supported in this copy of GDB."));
1022   else
1023     {
1024       struct command_line *l = get_command_line (python_control, "");
1025       struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
1026
1027       execute_control_command_untraced (l);
1028       do_cleanups (cleanups);
1029     }
1030 }
1031
1032 void
1033 eval_python_from_control_command (struct command_line *cmd)
1034 {
1035   error (_("Python scripting is not supported in this copy of GDB."));
1036 }
1037
1038 void
1039 source_python_script (const char *file)
1040 {
1041   throw_error (UNSUPPORTED_ERROR,
1042                _("Python scripting is not supported in this copy of GDB."));
1043 }
1044
1045 int
1046 gdbpy_should_stop (struct breakpoint_object *bp_obj)
1047 {
1048   internal_error (__FILE__, __LINE__,
1049                   _("gdbpy_should_stop called when Python scripting is  " \
1050                     "not supported."));
1051 }
1052
1053 int
1054 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
1055 {
1056   internal_error (__FILE__, __LINE__,
1057                   _("gdbpy_breakpoint_has_py_cond called when Python " \
1058                     "scripting is not supported."));
1059 }
1060
1061 #endif /* HAVE_PYTHON */
1062
1063 \f
1064
1065 /* Lists for 'maint set python' commands.  */
1066
1067 static struct cmd_list_element *maint_set_python_list;
1068 static struct cmd_list_element *maint_show_python_list;
1069
1070 /* Lists for 'set python' commands.  */
1071
1072 static struct cmd_list_element *user_set_python_list;
1073 static struct cmd_list_element *user_show_python_list;
1074
1075 /* Function for use by 'maint set python' prefix command.  */
1076
1077 static void
1078 maint_set_python (char *args, int from_tty)
1079 {
1080   help_list (maint_set_python_list, "maintenance set python ",
1081              class_deprecated, gdb_stdout);
1082 }
1083
1084 /* Function for use by 'maint show python' prefix command.  */
1085
1086 static void
1087 maint_show_python (char *args, int from_tty)
1088 {
1089   cmd_show_list (maint_show_python_list, from_tty, "");
1090 }
1091
1092 /* Function for use by 'set python' prefix command.  */
1093
1094 static void
1095 user_set_python (char *args, int from_tty)
1096 {
1097   help_list (user_set_python_list, "set python ", all_commands,
1098              gdb_stdout);
1099 }
1100
1101 /* Function for use by 'show python' prefix command.  */
1102
1103 static void
1104 user_show_python (char *args, int from_tty)
1105 {
1106   cmd_show_list (user_show_python_list, from_tty, "");
1107 }
1108
1109 /* Initialize the Python code.  */
1110
1111 /* Provide a prototype to silence -Wmissing-prototypes.  */
1112 extern initialize_file_ftype _initialize_python;
1113
1114 void
1115 _initialize_python (void)
1116 {
1117   char *cmd_name;
1118   struct cmd_list_element *cmd;
1119
1120   add_com ("python", class_obscure, python_command,
1121 #ifdef HAVE_PYTHON
1122            _("\
1123 Evaluate a Python command.\n\
1124 \n\
1125 The command can be given as an argument, for instance:\n\
1126 \n\
1127     python print 23\n\
1128 \n\
1129 If no argument is given, the following lines are read and used\n\
1130 as the Python commands.  Type a line containing \"end\" to indicate\n\
1131 the end of the command.")
1132 #else /* HAVE_PYTHON */
1133            _("\
1134 Evaluate a Python command.\n\
1135 \n\
1136 Python scripting is not supported in this copy of GDB.\n\
1137 This command is only a placeholder.")
1138 #endif /* HAVE_PYTHON */
1139            );
1140
1141   add_prefix_cmd ("python", no_class, maint_show_python,
1142                   _("Prefix command for python maintenance settings."),
1143                   &maint_show_python_list, "maintenance show python ", 0,
1144                   &maintenance_show_cmdlist);
1145   add_prefix_cmd ("python", no_class, maint_set_python,
1146                   _("Prefix command for python maintenance settings."),
1147                   &maint_set_python_list, "maintenance set python ", 0,
1148                   &maintenance_set_cmdlist);
1149
1150   add_setshow_boolean_cmd ("print-stack", class_maintenance,
1151                            &gdbpy_should_print_stack, _("\
1152 Enable or disable printing of Python stack dump on error."), _("\
1153 Show whether Python stack will be printed on error."), _("\
1154 Enables or disables printing of Python stack traces."),
1155                            NULL, NULL,
1156                            &maint_set_python_list,
1157                            &maint_show_python_list);
1158
1159   /* Deprecate maint set/show python print-stack in favour of
1160      non-maintenance alternatives.  */
1161   cmd_name = "print-stack";
1162   cmd = lookup_cmd (&cmd_name, maint_set_python_list, "", -1, 0);
1163   deprecate_cmd (cmd, "set python print-stack");
1164   cmd_name = "print-stack"; /* Reset name.  */
1165   cmd = lookup_cmd (&cmd_name, maint_show_python_list, "", -1, 0);
1166   deprecate_cmd (cmd, "show python print-stack");
1167
1168   /* Add set/show python print-stack.  */
1169   add_prefix_cmd ("python", no_class, user_show_python,
1170                   _("Prefix command for python preference settings."),
1171                   &user_show_python_list, "show python ", 0,
1172                   &showlist);
1173
1174   add_prefix_cmd ("python", no_class, user_set_python,
1175                   _("Prefix command for python preference settings."),
1176                   &user_set_python_list, "set python ", 0,
1177                   &setlist);
1178
1179   add_setshow_boolean_cmd ("print-stack", no_class,
1180                            &gdbpy_should_print_stack, _("\
1181 Enable or disable printing of Python stack dump on error."), _("\
1182 Show whether Python stack will be printed on error."), _("\
1183 Enables or disables printing of Python stack traces."),
1184                            NULL, NULL,
1185                            &user_set_python_list,
1186                            &user_show_python_list);
1187
1188 #ifdef HAVE_PYTHON
1189 #ifdef WITH_PYTHON_PATH
1190   /* Work around problem where python gets confused about where it is,
1191      and then can't find its libraries, etc.
1192      NOTE: Python assumes the following layout:
1193      /foo/bin/python
1194      /foo/lib/pythonX.Y/...
1195      This must be done before calling Py_Initialize.  */
1196   Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
1197                              SLASH_STRING, "python", NULL));
1198 #endif
1199
1200   Py_Initialize ();
1201   PyEval_InitThreads ();
1202
1203   gdb_module = Py_InitModule ("gdb", GdbMethods);
1204
1205   /* The casts to (char*) are for python 2.4.  */
1206   PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
1207   PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
1208   PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1209                               (char*) target_name);
1210
1211   /* Add stream constants.  */
1212   PyModule_AddIntConstant (gdb_module, "STDOUT", 0);
1213   PyModule_AddIntConstant (gdb_module, "STDERR", 1);
1214   PyModule_AddIntConstant (gdb_module, "STDLOG", 2);
1215   
1216   /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
1217      script below is run (depending on order of _initialize_* functions).
1218      Define the initial value of gdb.PYTHONDIR here.  */
1219   {
1220     char *gdb_pythondir;
1221
1222     gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
1223     PyModule_AddStringConstant (gdb_module, "PYTHONDIR", gdb_pythondir);
1224     xfree (gdb_pythondir);
1225   }
1226
1227   gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1228   PyModule_AddObject (gdb_module, "error", gdbpy_gdb_error);
1229
1230   gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1231                                                gdbpy_gdb_error, NULL);
1232   PyModule_AddObject (gdb_module, "MemoryError", gdbpy_gdb_memory_error);
1233
1234   gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1235   PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
1236
1237   gdbpy_initialize_auto_load ();
1238   gdbpy_initialize_values ();
1239   gdbpy_initialize_frames ();
1240   gdbpy_initialize_commands ();
1241   gdbpy_initialize_symbols ();
1242   gdbpy_initialize_symtabs ();
1243   gdbpy_initialize_blocks ();
1244   gdbpy_initialize_functions ();
1245   gdbpy_initialize_parameters ();
1246   gdbpy_initialize_types ();
1247   gdbpy_initialize_pspace ();
1248   gdbpy_initialize_objfile ();
1249   gdbpy_initialize_breakpoints ();
1250   gdbpy_initialize_lazy_string ();
1251   gdbpy_initialize_thread ();
1252   gdbpy_initialize_inferior ();
1253   gdbpy_initialize_events ();
1254
1255   gdbpy_initialize_eventregistry ();
1256   gdbpy_initialize_py_events ();
1257   gdbpy_initialize_event ();
1258   gdbpy_initialize_stop_event ();
1259   gdbpy_initialize_signal_event ();
1260   gdbpy_initialize_breakpoint_event ();
1261   gdbpy_initialize_continue_event ();
1262   gdbpy_initialize_exited_event ();
1263   gdbpy_initialize_thread_event ();
1264   gdbpy_initialize_new_objfile_event () ;
1265
1266   observer_attach_before_prompt (before_prompt_hook);
1267
1268   PyRun_SimpleString ("import gdb");
1269   PyRun_SimpleString ("gdb.pretty_printers = []");
1270
1271   gdbpy_to_string_cst = PyString_FromString ("to_string");
1272   gdbpy_children_cst = PyString_FromString ("children");
1273   gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1274   gdbpy_doc_cst = PyString_FromString ("__doc__");
1275   gdbpy_enabled_cst = PyString_FromString ("enabled");
1276   gdbpy_value_cst = PyString_FromString ("value");
1277
1278   /* Release the GIL while gdb runs.  */
1279   PyThreadState_Swap (NULL);
1280   PyEval_ReleaseLock ();
1281
1282 #endif /* HAVE_PYTHON */
1283 }
1284
1285 #ifdef HAVE_PYTHON
1286
1287 /* Perform the remaining python initializations.
1288    These must be done after GDB is at least mostly initialized.
1289    E.g., The "info pretty-printer" command needs the "info" prefix
1290    command installed.  */
1291
1292 void
1293 finish_python_initialization (void)
1294 {
1295   struct cleanup *cleanup;
1296
1297   cleanup = ensure_python_env (get_current_arch (), current_language);
1298
1299   PyRun_SimpleString ("\
1300 import os\n\
1301 import sys\n\
1302 \n\
1303 class GdbOutputFile:\n\
1304   def close(self):\n\
1305     # Do nothing.\n\
1306     return None\n\
1307 \n\
1308   def isatty(self):\n\
1309     return False\n\
1310 \n\
1311   def write(self, s):\n\
1312     gdb.write(s, stream=gdb.STDOUT)\n   \
1313 \n\
1314   def writelines(self, iterable):\n\
1315     for line in iterable:\n\
1316       self.write(line)\n\
1317 \n\
1318   def flush(self):\n\
1319     gdb.flush()\n\
1320 \n\
1321 sys.stdout = GdbOutputFile()\n\
1322 \n\
1323 class GdbOutputErrorFile:\n\
1324   def close(self):\n\
1325     # Do nothing.\n\
1326     return None\n\
1327 \n\
1328   def isatty(self):\n\
1329     return False\n\
1330 \n\
1331   def write(self, s):\n\
1332     gdb.write(s, stream=gdb.STDERR)\n           \
1333 \n\
1334   def writelines(self, iterable):\n\
1335     for line in iterable:\n\
1336       self.write(line)\n \
1337 \n\
1338   def flush(self):\n\
1339     gdb.flush()\n\
1340 \n\
1341 sys.stderr = GdbOutputErrorFile()\n\
1342 \n\
1343 # Ideally this would live in the gdb module, but it's intentionally written\n\
1344 # in python, and we need this to bootstrap the gdb module.\n\
1345 \n\
1346 def GdbSetPythonDirectory (dir):\n\
1347   \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1348   old_dir = gdb.PYTHONDIR\n\
1349   gdb.PYTHONDIR = dir\n\
1350   # GDB's python scripts are stored inside gdb.PYTHONDIR.  So insert\n\
1351   # that directory name at the start of sys.path to allow the Python\n\
1352   # interpreter to find them.\n\
1353   if old_dir in sys.path:\n\
1354     sys.path.remove (old_dir)\n\
1355   sys.path.insert (0, gdb.PYTHONDIR)\n\
1356 \n\
1357   # Tell python where to find submodules of gdb.\n\
1358   gdb.__path__ = [os.path.join (gdb.PYTHONDIR, 'gdb')]\n\
1359 \n\
1360   # The gdb module is implemented in C rather than in Python.  As a result,\n\
1361   # the associated __init.py__ script is not not executed by default when\n\
1362   # the gdb module gets imported.  Execute that script manually if it\n\
1363   # exists.\n\
1364   ipy = os.path.join (gdb.PYTHONDIR, 'gdb', '__init__.py')\n\
1365   if os.path.exists (ipy):\n\
1366     execfile (ipy)\n\
1367 \n\
1368 # Install the default gdb.PYTHONDIR.\n\
1369 GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
1370 # Default prompt hook does nothing.\n\
1371 prompt_hook = None\n\
1372 ");
1373
1374   do_cleanups (cleanup);
1375 }
1376
1377 #endif /* HAVE_PYTHON */
1378
1379 \f
1380
1381 #ifdef HAVE_PYTHON
1382
1383 static PyMethodDef GdbMethods[] =
1384 {
1385   { "history", gdbpy_history, METH_VARARGS,
1386     "Get a value from history" },
1387   { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1388     "Execute a gdb command" },
1389   { "parameter", gdbpy_parameter, METH_VARARGS,
1390     "Return a gdb parameter's value" },
1391
1392   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1393     "Return a tuple of all breakpoint objects" },
1394
1395   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1396     "Find the default visualizer for a Value." },
1397
1398   { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1399     "Return the current Progspace." },
1400   { "progspaces", gdbpy_progspaces, METH_NOARGS,
1401     "Return a sequence of all progspaces." },
1402
1403   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1404     "Return the current Objfile being loaded, or None." },
1405   { "objfiles", gdbpy_objfiles, METH_NOARGS,
1406     "Return a sequence of all loaded objfiles." },
1407
1408   { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
1409     "newest_frame () -> gdb.Frame.\n\
1410 Return the newest frame object." },
1411   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1412     "selected_frame () -> gdb.Frame.\n\
1413 Return the selected frame object." },
1414   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1415     "stop_reason_string (Integer) -> String.\n\
1416 Return a string explaining unwind stop reason." },
1417
1418   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1419     METH_VARARGS | METH_KEYWORDS,
1420     "lookup_type (name [, block]) -> type\n\
1421 Return a Type corresponding to the given name." },
1422   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1423     METH_VARARGS | METH_KEYWORDS,
1424     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1425 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1426 a boolean indicating if name is a field of the current implied argument\n\
1427 `this' (when the current language is object-oriented)." },
1428   { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
1429     METH_VARARGS | METH_KEYWORDS,
1430     "lookup_global_symbol (name [, domain]) -> symbol\n\
1431 Return the symbol corresponding to the given name (or None)." },
1432   { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1433     "Return the block containing the given pc value, or None." },
1434   { "solib_name", gdbpy_solib_name, METH_VARARGS,
1435     "solib_name (Long) -> String.\n\
1436 Return the name of the shared library holding a given address, or None." },
1437   { "decode_line", gdbpy_decode_line, METH_VARARGS,
1438     "decode_line (String) -> Tuple.  Decode a string argument the way\n\
1439 that 'break' or 'edit' does.  Return a tuple containing two elements.\n\
1440 The first element contains any unparsed portion of the String parameter\n\
1441 (or None if the string was fully parsed).  The second element contains\n\
1442 a tuple that contains all the locations that match, represented as\n\
1443 gdb.Symtab_and_line objects (or None)."},
1444   { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1445     "parse_and_eval (String) -> Value.\n\
1446 Parse String as an expression, evaluate it, and return the result as a Value."
1447   },
1448
1449   { "post_event", gdbpy_post_event, METH_VARARGS,
1450     "Post an event into gdb's event loop." },
1451
1452   { "target_charset", gdbpy_target_charset, METH_NOARGS,
1453     "target_charset () -> string.\n\
1454 Return the name of the current target charset." },
1455   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1456     "target_wide_charset () -> string.\n\
1457 Return the name of the current target wide charset." },
1458
1459   { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1460     "string_to_argv (String) -> Array.\n\
1461 Parse String and return an argv-like array.\n\
1462 Arguments are separate by spaces and may be quoted."
1463   },
1464   { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
1465     "Write a string using gdb's filtered stream." },
1466   { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
1467     "Flush gdb's filtered stdout stream." },
1468   { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1469     "selected_thread () -> gdb.InferiorThread.\n\
1470 Return the selected thread object." },
1471   { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
1472     "selected_inferior () -> gdb.Inferior.\n\
1473 Return the selected inferior object." },
1474   { "inferiors", gdbpy_inferiors, METH_NOARGS,
1475     "inferiors () -> (gdb.Inferior, ...).\n\
1476 Return a tuple containing all inferiors." },
1477   {NULL, NULL, 0, NULL}
1478 };
1479
1480 #endif /* HAVE_PYTHON */