* python/py-arch.c (gdbpy_initialize_arch): Return 'int'.
[platform/upstream/binutils.git] / gdb / python / python.c
1 /* General python/gdb code
2
3    Copyright (C) 2008-2013 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 #include "cli/cli-utils.h"
36
37 #include <ctype.h>
38
39 /* Declared constants and enum for python stack printing.  */
40 static const char python_excp_none[] = "none";
41 static const char python_excp_full[] = "full";
42 static const char python_excp_message[] = "message";
43
44 /* "set python print-stack" choices.  */
45 static const char *const python_excp_enums[] =
46   {
47     python_excp_none,
48     python_excp_full,
49     python_excp_message,
50     NULL
51   };
52
53 /* The exception printing variable.  'full' if we want to print the
54    error message and stack, 'none' if we want to print nothing, and
55    'message' if we only want to print the error message.  'message' is
56    the default.  */
57 static const char *gdbpy_should_print_stack = python_excp_message;
58
59 #ifdef HAVE_PYTHON
60
61 #include "libiberty.h"
62 #include "cli/cli-decode.h"
63 #include "charset.h"
64 #include "top.h"
65 #include "solib.h"
66 #include "python-internal.h"
67 #include "linespec.h"
68 #include "source.h"
69 #include "version.h"
70 #include "target.h"
71 #include "gdbthread.h"
72 #include "observer.h"
73 #include "interps.h"
74 #include "event-top.h"
75
76 /* True if Python has been successfully initialized, false
77    otherwise.  */
78
79 int gdb_python_initialized;
80
81 static PyMethodDef GdbMethods[];
82
83 #ifdef IS_PY3K
84 static struct PyModuleDef GdbModuleDef;
85 #endif
86
87 PyObject *gdb_module;
88 PyObject *gdb_python_module;
89
90 /* Some string constants we may wish to use.  */
91 PyObject *gdbpy_to_string_cst;
92 PyObject *gdbpy_children_cst;
93 PyObject *gdbpy_display_hint_cst;
94 PyObject *gdbpy_doc_cst;
95 PyObject *gdbpy_enabled_cst;
96 PyObject *gdbpy_value_cst;
97
98 /* The GdbError exception.  */
99 PyObject *gdbpy_gdberror_exc;
100
101 /* The `gdb.error' base class.  */
102 PyObject *gdbpy_gdb_error;
103
104 /* The `gdb.MemoryError' exception.  */
105 PyObject *gdbpy_gdb_memory_error;
106
107 /* Architecture and language to be used in callbacks from
108    the Python interpreter.  */
109 struct gdbarch *python_gdbarch;
110 const struct language_defn *python_language;
111
112 /* Restore global language and architecture and Python GIL state
113    when leaving the Python interpreter.  */
114
115 struct python_env
116 {
117   PyGILState_STATE state;
118   struct gdbarch *gdbarch;
119   const struct language_defn *language;
120   PyObject *error_type, *error_value, *error_traceback;
121 };
122
123 static void
124 restore_python_env (void *p)
125 {
126   struct python_env *env = (struct python_env *)p;
127
128   /* Leftover Python error is forbidden by Python Exception Handling.  */
129   if (PyErr_Occurred ())
130     {
131       /* This order is similar to the one calling error afterwards. */
132       gdbpy_print_stack ();
133       warning (_("internal error: Unhandled Python exception"));
134     }
135
136   PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
137
138   PyGILState_Release (env->state);
139   python_gdbarch = env->gdbarch;
140   python_language = env->language;
141   xfree (env);
142 }
143
144 /* Called before entering the Python interpreter to install the
145    current language and architecture to be used for Python values.  */
146
147 struct cleanup *
148 ensure_python_env (struct gdbarch *gdbarch,
149                    const struct language_defn *language)
150 {
151   struct python_env *env = xmalloc (sizeof *env);
152
153   env->state = PyGILState_Ensure ();
154   env->gdbarch = python_gdbarch;
155   env->language = python_language;
156
157   python_gdbarch = gdbarch;
158   python_language = language;
159
160   /* Save it and ensure ! PyErr_Occurred () afterwards.  */
161   PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
162   
163   return make_cleanup (restore_python_env, env);
164 }
165
166 /* Clear the quit flag.  */
167
168 void
169 clear_quit_flag (void)
170 {
171   /* This clears the flag as a side effect.  */
172   PyOS_InterruptOccurred ();
173 }
174
175 /* Set the quit flag.  */
176
177 void
178 set_quit_flag (void)
179 {
180   PyErr_SetInterrupt ();
181 }
182
183 /* Return true if the quit flag has been set, false otherwise.  */
184
185 int
186 check_quit_flag (void)
187 {
188   return PyOS_InterruptOccurred ();
189 }
190
191 /* Evaluate a Python command like PyRun_SimpleString, but uses
192    Py_single_input which prints the result of expressions, and does
193    not automatically print the stack on errors.  */
194
195 static int
196 eval_python_command (const char *command)
197 {
198   PyObject *m, *d, *v;
199
200   m = PyImport_AddModule ("__main__");
201   if (m == NULL)
202     return -1;
203
204   d = PyModule_GetDict (m);
205   if (d == NULL)
206     return -1;
207   v = PyRun_StringFlags (command, Py_single_input, d, d, NULL);
208   if (v == NULL)
209     return -1;
210
211   Py_DECREF (v);
212 #ifndef IS_PY3K
213   if (Py_FlushLine ())
214     PyErr_Clear ();
215 #endif
216
217   return 0;
218 }
219
220 /* Implementation of the gdb "python-interactive" command.  */
221
222 static void
223 python_interactive_command (char *arg, int from_tty)
224 {
225   struct cleanup *cleanup;
226   int err;
227
228   cleanup = make_cleanup_restore_integer (&interpreter_async);
229   interpreter_async = 0;
230
231   arg = skip_spaces (arg);
232
233   ensure_python_env (get_current_arch (), current_language);
234
235   if (arg && *arg)
236     {
237       int len = strlen (arg);
238       char *script = xmalloc (len + 2);
239
240       strcpy (script, arg);
241       script[len] = '\n';
242       script[len + 1] = '\0';
243       err = eval_python_command (script);
244       xfree (script);
245     }
246   else
247     {
248       err = PyRun_InteractiveLoop (instream, "<stdin>");
249       dont_repeat ();
250     }
251
252   if (err)
253     {
254       gdbpy_print_stack ();
255       error (_("Error while executing Python code."));
256     }
257
258   do_cleanups (cleanup);
259 }
260
261 /* A wrapper around PyRun_SimpleFile.  FILE is the Python script to run
262    named FILENAME.
263
264    On Windows hosts few users would build Python themselves (this is no
265    trivial task on this platform), and thus use binaries built by
266    someone else instead.  There may happen situation where the Python
267    library and GDB are using two different versions of the C runtime
268    library.  Python, being built with VC, would use one version of the
269    msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
270    A FILE * from one runtime does not necessarily operate correctly in
271    the other runtime.
272
273    To work around this potential issue, we create on Windows hosts the
274    FILE object using Python routines, thus making sure that it is
275    compatible with the Python library.  */
276
277 static void
278 python_run_simple_file (FILE *file, const char *filename)
279 {
280 #ifndef _WIN32
281
282   PyRun_SimpleFile (file, filename);
283
284 #else /* _WIN32 */
285
286   char *full_path;
287   PyObject *python_file;
288   struct cleanup *cleanup;
289
290   /* Because we have a string for a filename, and are using Python to
291      open the file, we need to expand any tilde in the path first.  */
292   full_path = tilde_expand (filename);
293   cleanup = make_cleanup (xfree, full_path);
294   python_file = PyFile_FromString (full_path, "r");
295   if (! python_file)
296     {
297       do_cleanups (cleanup);
298       gdbpy_print_stack ();
299       error (_("Error while opening file: %s"), full_path);
300     }
301  
302   make_cleanup_py_decref (python_file);
303   PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
304   do_cleanups (cleanup);
305
306 #endif /* _WIN32 */
307 }
308
309 /* Given a command_line, return a command string suitable for passing
310    to Python.  Lines in the string are separated by newlines.  The
311    return value is allocated using xmalloc and the caller is
312    responsible for freeing it.  */
313
314 static char *
315 compute_python_string (struct command_line *l)
316 {
317   struct command_line *iter;
318   char *script = NULL;
319   int size = 0;
320   int here;
321
322   for (iter = l; iter; iter = iter->next)
323     size += strlen (iter->line) + 1;
324
325   script = xmalloc (size + 1);
326   here = 0;
327   for (iter = l; iter; iter = iter->next)
328     {
329       int len = strlen (iter->line);
330
331       strcpy (&script[here], iter->line);
332       here += len;
333       script[here++] = '\n';
334     }
335   script[here] = '\0';
336   return script;
337 }
338
339 /* Take a command line structure representing a 'python' command, and
340    evaluate its body using the Python interpreter.  */
341
342 void
343 eval_python_from_control_command (struct command_line *cmd)
344 {
345   int ret;
346   char *script;
347   struct cleanup *cleanup;
348
349   if (cmd->body_count != 1)
350     error (_("Invalid \"python\" block structure."));
351
352   cleanup = ensure_python_env (get_current_arch (), current_language);
353
354   script = compute_python_string (cmd->body_list[0]);
355   ret = PyRun_SimpleString (script);
356   xfree (script);
357   if (ret)
358     error (_("Error while executing Python code."));
359
360   do_cleanups (cleanup);
361 }
362
363 /* Implementation of the gdb "python" command.  */
364
365 static void
366 python_command (char *arg, int from_tty)
367 {
368   struct cleanup *cleanup;
369
370   cleanup = ensure_python_env (get_current_arch (), current_language);
371
372   make_cleanup_restore_integer (&interpreter_async);
373   interpreter_async = 0;
374
375   arg = skip_spaces (arg);
376   if (arg && *arg)
377     {
378       if (PyRun_SimpleString (arg))
379         error (_("Error while executing Python code."));
380     }
381   else
382     {
383       struct command_line *l = get_command_line (python_control, "");
384
385       make_cleanup_free_command_lines (&l);
386       execute_control_command_untraced (l);
387     }
388
389   do_cleanups (cleanup);
390 }
391
392 \f
393
394 /* Transform a gdb parameters's value into a Python value.  May return
395    NULL (and set a Python exception) on error.  Helper function for
396    get_parameter.  */
397 PyObject *
398 gdbpy_parameter_value (enum var_types type, void *var)
399 {
400   switch (type)
401     {
402     case var_string:
403     case var_string_noescape:
404     case var_optional_filename:
405     case var_filename:
406     case var_enum:
407       {
408         char *str = * (char **) var;
409
410         if (! str)
411           str = "";
412         return PyString_Decode (str, strlen (str), host_charset (), NULL);
413       }
414
415     case var_boolean:
416       {
417         if (* (int *) var)
418           Py_RETURN_TRUE;
419         else
420           Py_RETURN_FALSE;
421       }
422
423     case var_auto_boolean:
424       {
425         enum auto_boolean ab = * (enum auto_boolean *) var;
426
427         if (ab == AUTO_BOOLEAN_TRUE)
428           Py_RETURN_TRUE;
429         else if (ab == AUTO_BOOLEAN_FALSE)
430           Py_RETURN_FALSE;
431         else
432           Py_RETURN_NONE;
433       }
434
435     case var_integer:
436       if ((* (int *) var) == INT_MAX)
437         Py_RETURN_NONE;
438       /* Fall through.  */
439     case var_zinteger:
440       return PyLong_FromLong (* (int *) var);
441
442     case var_uinteger:
443       {
444         unsigned int val = * (unsigned int *) var;
445
446         if (val == UINT_MAX)
447           Py_RETURN_NONE;
448         return PyLong_FromUnsignedLong (val);
449       }
450     }
451
452   return PyErr_Format (PyExc_RuntimeError, 
453                        _("Programmer error: unhandled type."));
454 }
455
456 /* A Python function which returns a gdb parameter's value as a Python
457    value.  */
458
459 PyObject *
460 gdbpy_parameter (PyObject *self, PyObject *args)
461 {
462   struct cmd_list_element *alias, *prefix, *cmd;
463   const char *arg;
464   char *newarg;
465   int found = -1;
466   volatile struct gdb_exception except;
467
468   if (! PyArg_ParseTuple (args, "s", &arg))
469     return NULL;
470
471   newarg = concat ("show ", arg, (char *) NULL);
472
473   TRY_CATCH (except, RETURN_MASK_ALL)
474     {
475       found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
476     }
477   xfree (newarg);
478   GDB_PY_HANDLE_EXCEPTION (except);
479   if (!found)
480     return PyErr_Format (PyExc_RuntimeError,
481                          _("Could not find parameter `%s'."), arg);
482
483   if (! cmd->var)
484     return PyErr_Format (PyExc_RuntimeError, 
485                          _("`%s' is not a parameter."), arg);
486   return gdbpy_parameter_value (cmd->var_type, cmd->var);
487 }
488
489 /* Wrapper for target_charset.  */
490
491 static PyObject *
492 gdbpy_target_charset (PyObject *self, PyObject *args)
493 {
494   const char *cset = target_charset (python_gdbarch);
495
496   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
497 }
498
499 /* Wrapper for target_wide_charset.  */
500
501 static PyObject *
502 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
503 {
504   const char *cset = target_wide_charset (python_gdbarch);
505
506   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
507 }
508
509 /* A Python function which evaluates a string using the gdb CLI.  */
510
511 static PyObject *
512 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
513 {
514   const char *arg;
515   PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
516   int from_tty, to_string;
517   volatile struct gdb_exception except;
518   static char *keywords[] = {"command", "from_tty", "to_string", NULL };
519   char *result = NULL;
520
521   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
522                                      &PyBool_Type, &from_tty_obj,
523                                      &PyBool_Type, &to_string_obj))
524     return NULL;
525
526   from_tty = 0;
527   if (from_tty_obj)
528     {
529       int cmp = PyObject_IsTrue (from_tty_obj);
530       if (cmp < 0)
531         return NULL;
532       from_tty = cmp;
533     }
534
535   to_string = 0;
536   if (to_string_obj)
537     {
538       int cmp = PyObject_IsTrue (to_string_obj);
539       if (cmp < 0)
540         return NULL;
541       to_string = cmp;
542     }
543
544   TRY_CATCH (except, RETURN_MASK_ALL)
545     {
546       /* Copy the argument text in case the command modifies it.  */
547       char *copy = xstrdup (arg);
548       struct cleanup *cleanup = make_cleanup (xfree, copy);
549
550       make_cleanup_restore_integer (&interpreter_async);
551       interpreter_async = 0;
552
553       prevent_dont_repeat ();
554       if (to_string)
555         result = execute_command_to_string (copy, from_tty);
556       else
557         {
558           result = NULL;
559           execute_command (copy, from_tty);
560         }
561
562       do_cleanups (cleanup);
563     }
564   GDB_PY_HANDLE_EXCEPTION (except);
565
566   /* Do any commands attached to breakpoint we stopped at.  */
567   bpstat_do_actions ();
568
569   if (result)
570     {
571       PyObject *r = PyString_FromString (result);
572       xfree (result);
573       return r;
574     }
575   Py_RETURN_NONE;
576 }
577
578 /* Implementation of gdb.solib_name (Long) -> String.
579    Returns the name of the shared library holding a given address, or None.  */
580
581 static PyObject *
582 gdbpy_solib_name (PyObject *self, PyObject *args)
583 {
584   char *soname;
585   PyObject *str_obj;
586   gdb_py_longest pc;
587
588   if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
589     return NULL;
590
591   soname = solib_name_from_address (current_program_space, pc);
592   if (soname)
593     str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
594   else
595     {
596       str_obj = Py_None;
597       Py_INCREF (Py_None);
598     }
599
600   return str_obj;
601 }
602
603 /* A Python function which is a wrapper for decode_line_1.  */
604
605 static PyObject *
606 gdbpy_decode_line (PyObject *self, PyObject *args)
607 {
608   struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
609                                                   appease gcc.  */
610   struct symtab_and_line sal;
611   const char *arg = NULL;
612   char *copy_to_free = NULL, *copy = NULL;
613   struct cleanup *cleanups;
614   PyObject *result = NULL;
615   PyObject *return_result = NULL;
616   PyObject *unparsed = NULL;
617   volatile struct gdb_exception except;
618
619   if (! PyArg_ParseTuple (args, "|s", &arg))
620     return NULL;
621
622   cleanups = make_cleanup (null_cleanup, NULL);
623
624   sals.sals = NULL;
625   TRY_CATCH (except, RETURN_MASK_ALL)
626     {
627       if (arg)
628         {
629           copy = xstrdup (arg);
630           copy_to_free = copy;
631           sals = decode_line_1 (&copy, 0, 0, 0);
632         }
633       else
634         {
635           set_default_source_symtab_and_line ();
636           sal = get_current_source_symtab_and_line ();
637           sals.sals = &sal;
638           sals.nelts = 1;
639         }
640     }
641
642   if (sals.sals != NULL && sals.sals != &sal)
643     {
644       make_cleanup (xfree, copy_to_free);
645       make_cleanup (xfree, sals.sals);
646     }
647
648   if (except.reason < 0)
649     {
650       do_cleanups (cleanups);
651       /* We know this will always throw.  */
652       GDB_PY_HANDLE_EXCEPTION (except);
653     }
654
655   if (sals.nelts)
656     {
657       int i;
658
659       result = PyTuple_New (sals.nelts);
660       if (! result)
661         goto error;
662       for (i = 0; i < sals.nelts; ++i)
663         {
664           PyObject *obj;
665
666           obj = symtab_and_line_to_sal_object (sals.sals[i]);
667           if (! obj)
668             {
669               Py_DECREF (result);
670               goto error;
671             }
672
673           PyTuple_SetItem (result, i, obj);
674         }
675     }
676   else
677     {
678       result = Py_None;
679       Py_INCREF (Py_None);
680     }
681
682   return_result = PyTuple_New (2);
683   if (! return_result)
684     {
685       Py_DECREF (result);
686       goto error;
687     }
688
689   if (copy && strlen (copy) > 0)
690     {
691       unparsed = PyString_FromString (copy);
692       if (unparsed == NULL)
693         {
694           Py_DECREF (result);
695           Py_DECREF (return_result);
696           return_result = NULL;
697           goto error;
698         }
699     }
700   else
701     {
702       unparsed = Py_None;
703       Py_INCREF (Py_None);
704     }
705
706   PyTuple_SetItem (return_result, 0, unparsed);
707   PyTuple_SetItem (return_result, 1, result);
708
709  error:
710   do_cleanups (cleanups);
711
712   return return_result;
713 }
714
715 /* Parse a string and evaluate it as an expression.  */
716 static PyObject *
717 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
718 {
719   const char *expr_str;
720   struct value *result = NULL;
721   volatile struct gdb_exception except;
722
723   if (!PyArg_ParseTuple (args, "s", &expr_str))
724     return NULL;
725
726   TRY_CATCH (except, RETURN_MASK_ALL)
727     {
728       result = parse_and_eval (expr_str);
729     }
730   GDB_PY_HANDLE_EXCEPTION (except);
731
732   return value_to_value_object (result);
733 }
734
735 /* Implementation of gdb.find_pc_line function.
736    Returns the gdb.Symtab_and_line object corresponding to a PC value.  */
737
738 static PyObject *
739 gdbpy_find_pc_line (PyObject *self, PyObject *args)
740 {
741   gdb_py_ulongest pc_llu;
742   volatile struct gdb_exception except;
743   PyObject *result = NULL; /* init for gcc -Wall */
744
745   if (!PyArg_ParseTuple (args, GDB_PY_LLU_ARG, &pc_llu))
746     return NULL;
747
748   TRY_CATCH (except, RETURN_MASK_ALL)
749     {
750       struct symtab_and_line sal;
751       CORE_ADDR pc;
752
753       pc = (CORE_ADDR) pc_llu;
754       sal = find_pc_line (pc, 0);
755       result = symtab_and_line_to_sal_object (sal);
756     }
757   GDB_PY_HANDLE_EXCEPTION (except);
758
759   return result;
760 }
761
762 /* Read a file as Python code.
763    FILE is the file to run.  FILENAME is name of the file FILE.
764    This does not throw any errors.  If an exception occurs python will print
765    the traceback and clear the error indicator.  */
766
767 void
768 source_python_script (FILE *file, const char *filename)
769 {
770   struct cleanup *cleanup;
771
772   cleanup = ensure_python_env (get_current_arch (), current_language);
773   python_run_simple_file (file, filename);
774   do_cleanups (cleanup);
775 }
776
777 \f
778
779 /* Posting and handling events.  */
780
781 /* A single event.  */
782 struct gdbpy_event
783 {
784   /* The Python event.  This is just a callable object.  */
785   PyObject *event;
786   /* The next event.  */
787   struct gdbpy_event *next;
788 };
789
790 /* All pending events.  */
791 static struct gdbpy_event *gdbpy_event_list;
792 /* The final link of the event list.  */
793 static struct gdbpy_event **gdbpy_event_list_end;
794
795 /* We use a file handler, and not an async handler, so that we can
796    wake up the main thread even when it is blocked in poll().  */
797 static struct serial *gdbpy_event_fds[2];
798
799 /* The file handler callback.  This reads from the internal pipe, and
800    then processes the Python event queue.  This will always be run in
801    the main gdb thread.  */
802
803 static void
804 gdbpy_run_events (struct serial *scb, void *context)
805 {
806   struct cleanup *cleanup;
807
808   cleanup = ensure_python_env (get_current_arch (), current_language);
809
810   /* Flush the fd.  Do this before flushing the events list, so that
811      any new event post afterwards is sure to re-awake the event
812      loop.  */
813   while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
814     ;
815
816   while (gdbpy_event_list)
817     {
818       /* Dispatching the event might push a new element onto the event
819          loop, so we update here "atomically enough".  */
820       struct gdbpy_event *item = gdbpy_event_list;
821       gdbpy_event_list = gdbpy_event_list->next;
822       if (gdbpy_event_list == NULL)
823         gdbpy_event_list_end = &gdbpy_event_list;
824
825       /* Ignore errors.  */
826       if (PyObject_CallObject (item->event, NULL) == NULL)
827         PyErr_Clear ();
828
829       Py_DECREF (item->event);
830       xfree (item);
831     }
832
833   do_cleanups (cleanup);
834 }
835
836 /* Submit an event to the gdb thread.  */
837 static PyObject *
838 gdbpy_post_event (PyObject *self, PyObject *args)
839 {
840   struct gdbpy_event *event;
841   PyObject *func;
842   int wakeup;
843
844   if (!PyArg_ParseTuple (args, "O", &func))
845     return NULL;
846
847   if (!PyCallable_Check (func))
848     {
849       PyErr_SetString (PyExc_RuntimeError, 
850                        _("Posted event is not callable"));
851       return NULL;
852     }
853
854   Py_INCREF (func);
855
856   /* From here until the end of the function, we have the GIL, so we
857      can operate on our global data structures without worrying.  */
858   wakeup = gdbpy_event_list == NULL;
859
860   event = XNEW (struct gdbpy_event);
861   event->event = func;
862   event->next = NULL;
863   *gdbpy_event_list_end = event;
864   gdbpy_event_list_end = &event->next;
865
866   /* Wake up gdb when needed.  */
867   if (wakeup)
868     {
869       char c = 'q';             /* Anything. */
870
871       if (serial_write (gdbpy_event_fds[1], &c, 1))
872         return PyErr_SetFromErrno (PyExc_IOError);
873     }
874
875   Py_RETURN_NONE;
876 }
877
878 /* Initialize the Python event handler.  */
879 static int
880 gdbpy_initialize_events (void)
881 {
882   if (serial_pipe (gdbpy_event_fds) == 0)
883     {
884       gdbpy_event_list_end = &gdbpy_event_list;
885       serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
886     }
887
888   return 0;
889 }
890
891 \f
892
893 static void
894 before_prompt_hook (const char *current_gdb_prompt)
895 {
896   struct cleanup *cleanup;
897   char *prompt = NULL;
898
899   cleanup = ensure_python_env (get_current_arch (), current_language);
900
901   if (gdb_python_module
902       && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
903     {
904       PyObject *hook;
905
906       hook = PyObject_GetAttrString (gdb_python_module, "prompt_hook");
907       if (hook == NULL)
908         goto fail;
909
910       make_cleanup_py_decref (hook);
911
912       if (PyCallable_Check (hook))
913         {
914           PyObject *result;
915           PyObject *current_prompt;
916
917           current_prompt = PyString_FromString (current_gdb_prompt);
918           if (current_prompt == NULL)
919             goto fail;
920
921           result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);
922
923           Py_DECREF (current_prompt);
924
925           if (result == NULL)
926             goto fail;
927
928           make_cleanup_py_decref (result);
929
930           /* Return type should be None, or a String.  If it is None,
931              fall through, we will not set a prompt.  If it is a
932              string, set  PROMPT.  Anything else, set an exception.  */
933           if (result != Py_None && ! PyString_Check (result))
934             {
935               PyErr_Format (PyExc_RuntimeError,
936                             _("Return from prompt_hook must " \
937                               "be either a Python string, or None"));
938               goto fail;
939             }
940
941           if (result != Py_None)
942             {
943               prompt = python_string_to_host_string (result);
944
945               if (prompt == NULL)
946                 goto fail;
947               else
948                 make_cleanup (xfree, prompt);
949             }
950         }
951     }
952
953   /* If a prompt has been set, PROMPT will not be NULL.  If it is
954      NULL, do not set the prompt.  */
955   if (prompt != NULL)
956     set_prompt (prompt);
957
958   do_cleanups (cleanup);
959   return;
960
961  fail:
962   gdbpy_print_stack ();
963   do_cleanups (cleanup);
964   return;
965 }
966
967 \f
968
969 /* Printing.  */
970
971 /* A python function to write a single string using gdb's filtered
972    output stream .  The optional keyword STREAM can be used to write
973    to a particular stream.  The default stream is to gdb_stdout.  */
974
975 static PyObject *
976 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
977 {
978   const char *arg;
979   static char *keywords[] = {"text", "stream", NULL };
980   int stream_type = 0;
981   volatile struct gdb_exception except;
982   
983   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
984                                      &stream_type))
985     return NULL;
986
987   TRY_CATCH (except, RETURN_MASK_ALL)
988     {
989       switch (stream_type)
990         {
991         case 1:
992           {
993             fprintf_filtered (gdb_stderr, "%s", arg);
994             break;
995           }
996         case 2:
997           {
998             fprintf_filtered (gdb_stdlog, "%s", arg);
999             break;
1000           }
1001         default:
1002           fprintf_filtered (gdb_stdout, "%s", arg);
1003         }
1004     }
1005   GDB_PY_HANDLE_EXCEPTION (except);
1006      
1007   Py_RETURN_NONE;
1008 }
1009
1010 /* A python function to flush a gdb stream.  The optional keyword
1011    STREAM can be used to flush a particular stream.  The default stream
1012    is gdb_stdout.  */
1013
1014 static PyObject *
1015 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
1016 {
1017   static char *keywords[] = {"stream", NULL };
1018   int stream_type = 0;
1019   
1020   if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1021                                      &stream_type))
1022     return NULL;
1023
1024   switch (stream_type)
1025     {
1026     case 1:
1027       {
1028         gdb_flush (gdb_stderr);
1029         break;
1030       }
1031     case 2:
1032       {
1033         gdb_flush (gdb_stdlog);
1034         break;
1035       }
1036     default:
1037       gdb_flush (gdb_stdout);
1038     }
1039      
1040   Py_RETURN_NONE;
1041 }
1042
1043 /* Print a python exception trace, print just a message, or print
1044    nothing and clear the python exception, depending on
1045    gdbpy_should_print_stack.  Only call this if a python exception is
1046    set.  */
1047 void
1048 gdbpy_print_stack (void)
1049 {
1050   volatile struct gdb_exception except;
1051
1052   /* Print "none", just clear exception.  */
1053   if (gdbpy_should_print_stack == python_excp_none)
1054     {
1055       PyErr_Clear ();
1056     }
1057   /* Print "full" message and backtrace.  */
1058   else if (gdbpy_should_print_stack == python_excp_full)
1059     {
1060       PyErr_Print ();
1061       /* PyErr_Print doesn't necessarily end output with a newline.
1062          This works because Python's stdout/stderr is fed through
1063          printf_filtered.  */
1064       TRY_CATCH (except, RETURN_MASK_ALL)
1065         {
1066           begin_line ();
1067         }
1068     }
1069   /* Print "message", just error print message.  */
1070   else
1071     {
1072       PyObject *ptype, *pvalue, *ptraceback;
1073       char *msg = NULL, *type = NULL;
1074
1075       PyErr_Fetch (&ptype, &pvalue, &ptraceback);
1076
1077       /* Fetch the error message contained within ptype, pvalue.  */
1078       msg = gdbpy_exception_to_string (ptype, pvalue);
1079       type = gdbpy_obj_to_string (ptype);
1080
1081       TRY_CATCH (except, RETURN_MASK_ALL)
1082         {
1083           if (msg == NULL)
1084             {
1085               /* An error occurred computing the string representation of the
1086                  error message.  */
1087               fprintf_filtered (gdb_stderr,
1088                                 _("Error occurred computing Python error" \
1089                                   "message.\n"));
1090             }
1091           else
1092             fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
1093                               type, msg);
1094         }
1095
1096       Py_XDECREF (ptype);
1097       Py_XDECREF (pvalue);
1098       Py_XDECREF (ptraceback);
1099       xfree (msg);
1100     }
1101 }
1102
1103 \f
1104
1105 /* Return the current Progspace.
1106    There always is one.  */
1107
1108 static PyObject *
1109 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
1110 {
1111   PyObject *result;
1112
1113   result = pspace_to_pspace_object (current_program_space);
1114   if (result)
1115     Py_INCREF (result);
1116   return result;
1117 }
1118
1119 /* Return a sequence holding all the Progspaces.  */
1120
1121 static PyObject *
1122 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1123 {
1124   struct program_space *ps;
1125   PyObject *list;
1126
1127   list = PyList_New (0);
1128   if (!list)
1129     return NULL;
1130
1131   ALL_PSPACES (ps)
1132   {
1133     PyObject *item = pspace_to_pspace_object (ps);
1134
1135     if (!item || PyList_Append (list, item) == -1)
1136       {
1137         Py_DECREF (list);
1138         return NULL;
1139       }
1140   }
1141
1142   return list;
1143 }
1144
1145 \f
1146
1147 /* The "current" objfile.  This is set when gdb detects that a new
1148    objfile has been loaded.  It is only set for the duration of a call to
1149    source_python_script_for_objfile; it is NULL at other times.  */
1150 static struct objfile *gdbpy_current_objfile;
1151
1152 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1153    as Python code.  This does not throw any errors.  If an exception
1154    occurs python will print the traceback and clear the error indicator.  */
1155
1156 void
1157 source_python_script_for_objfile (struct objfile *objfile, FILE *file,
1158                                   const char *filename)
1159 {
1160   struct cleanup *cleanups;
1161
1162   cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
1163   gdbpy_current_objfile = objfile;
1164
1165   python_run_simple_file (file, filename);
1166
1167   do_cleanups (cleanups);
1168   gdbpy_current_objfile = NULL;
1169 }
1170
1171 /* Return the current Objfile, or None if there isn't one.  */
1172
1173 static PyObject *
1174 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1175 {
1176   PyObject *result;
1177
1178   if (! gdbpy_current_objfile)
1179     Py_RETURN_NONE;
1180
1181   result = objfile_to_objfile_object (gdbpy_current_objfile);
1182   if (result)
1183     Py_INCREF (result);
1184   return result;
1185 }
1186
1187 /* Return a sequence holding all the Objfiles.  */
1188
1189 static PyObject *
1190 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
1191 {
1192   struct objfile *objf;
1193   PyObject *list;
1194
1195   list = PyList_New (0);
1196   if (!list)
1197     return NULL;
1198
1199   ALL_OBJFILES (objf)
1200   {
1201     PyObject *item = objfile_to_objfile_object (objf);
1202
1203     if (!item || PyList_Append (list, item) == -1)
1204       {
1205         Py_DECREF (list);
1206         return NULL;
1207       }
1208   }
1209
1210   return list;
1211 }
1212
1213 /* Compute the list of active type printers and return it.  The result
1214    of this function can be passed to apply_type_printers, and should
1215    be freed by free_type_printers.  */
1216
1217 void *
1218 start_type_printers (void)
1219 {
1220   struct cleanup *cleanups;
1221   PyObject *type_module, *func, *result_obj = NULL;
1222
1223   cleanups = ensure_python_env (get_current_arch (), current_language);
1224
1225   type_module = PyImport_ImportModule ("gdb.types");
1226   if (type_module == NULL)
1227     {
1228       gdbpy_print_stack ();
1229       goto done;
1230     }
1231   make_cleanup_py_decref (type_module);
1232
1233   func = PyObject_GetAttrString (type_module, "get_type_recognizers");
1234   if (func == NULL)
1235     {
1236       gdbpy_print_stack ();
1237       goto done;
1238     }
1239   make_cleanup_py_decref (func);
1240
1241   result_obj = PyObject_CallFunctionObjArgs (func, (char *) NULL);
1242   if (result_obj == NULL)
1243     gdbpy_print_stack ();
1244
1245  done:
1246   do_cleanups (cleanups);
1247   return result_obj;
1248 }
1249
1250 /* If TYPE is recognized by some type printer, return a newly
1251    allocated string holding the type's replacement name.  The caller
1252    is responsible for freeing the string.  Otherwise, return NULL.
1253
1254    This function has a bit of a funny name, since it actually applies
1255    recognizers, but this seemed clearer given the start_type_printers
1256    and free_type_printers functions.  */
1257
1258 char *
1259 apply_type_printers (void *printers, struct type *type)
1260 {
1261   struct cleanup *cleanups;
1262   PyObject *type_obj, *type_module, *func, *result_obj;
1263   PyObject *printers_obj = printers;
1264   char *result = NULL;
1265
1266   if (printers_obj == NULL)
1267     return NULL;
1268
1269   cleanups = ensure_python_env (get_current_arch (), current_language);
1270
1271   type_obj = type_to_type_object (type);
1272   if (type_obj == NULL)
1273     {
1274       gdbpy_print_stack ();
1275       goto done;
1276     }
1277   make_cleanup_py_decref (type_obj);
1278
1279   type_module = PyImport_ImportModule ("gdb.types");
1280   if (type_module == NULL)
1281     {
1282       gdbpy_print_stack ();
1283       goto done;
1284     }
1285   make_cleanup_py_decref (type_module);
1286
1287   func = PyObject_GetAttrString (type_module, "apply_type_recognizers");
1288   if (func == NULL)
1289     {
1290       gdbpy_print_stack ();
1291       goto done;
1292     }
1293   make_cleanup_py_decref (func);
1294
1295   result_obj = PyObject_CallFunctionObjArgs (func, printers_obj,
1296                                              type_obj, (char *) NULL);
1297   if (result_obj == NULL)
1298     {
1299       gdbpy_print_stack ();
1300       goto done;
1301     }
1302   make_cleanup_py_decref (result_obj);
1303
1304   if (result_obj != Py_None)
1305     {
1306       result = python_string_to_host_string (result_obj);
1307       if (result == NULL)
1308         gdbpy_print_stack ();
1309     }
1310
1311  done:
1312   do_cleanups (cleanups);
1313   return result;
1314 }
1315
1316 /* Free the result of start_type_printers.  */
1317
1318 void
1319 free_type_printers (void *arg)
1320 {
1321   struct cleanup *cleanups;
1322   PyObject *printers = arg;
1323
1324   if (printers == NULL)
1325     return;
1326
1327   cleanups = ensure_python_env (get_current_arch (), current_language);
1328   Py_DECREF (printers);
1329   do_cleanups (cleanups);
1330 }
1331
1332 #else /* HAVE_PYTHON */
1333
1334 /* Dummy implementation of the gdb "python-interactive" and "python"
1335    command. */
1336
1337 static void
1338 python_interactive_command (char *arg, int from_tty)
1339 {
1340   arg = skip_spaces (arg);
1341   if (arg && *arg)
1342     error (_("Python scripting is not supported in this copy of GDB."));
1343   else
1344     {
1345       struct command_line *l = get_command_line (python_control, "");
1346       struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
1347
1348       execute_control_command_untraced (l);
1349       do_cleanups (cleanups);
1350     }
1351 }
1352
1353 static void
1354 python_command (char *arg, int from_tty)
1355 {
1356   python_interactive_command (arg, from_tty);
1357 }
1358
1359 void
1360 eval_python_from_control_command (struct command_line *cmd)
1361 {
1362   error (_("Python scripting is not supported in this copy of GDB."));
1363 }
1364
1365 void
1366 source_python_script (FILE *file, const char *filename)
1367 {
1368   throw_error (UNSUPPORTED_ERROR,
1369                _("Python scripting is not supported in this copy of GDB."));
1370 }
1371
1372 int
1373 gdbpy_should_stop (struct breakpoint_object *bp_obj)
1374 {
1375   internal_error (__FILE__, __LINE__,
1376                   _("gdbpy_should_stop called when Python scripting is  " \
1377                     "not supported."));
1378 }
1379
1380 int
1381 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
1382 {
1383   internal_error (__FILE__, __LINE__,
1384                   _("gdbpy_breakpoint_has_py_cond called when Python " \
1385                     "scripting is not supported."));
1386 }
1387
1388 void *
1389 start_type_printers (void)
1390 {
1391   return NULL;
1392 }
1393
1394 char *
1395 apply_type_printers (void *ignore, struct type *type)
1396 {
1397   return NULL;
1398 }
1399
1400 void
1401 free_type_printers (void *arg)
1402 {
1403 }
1404
1405 enum py_bt_status
1406 apply_frame_filter (struct frame_info *frame, int flags,
1407                     enum py_frame_args args_type,
1408                     struct ui_out *out, int frame_low,
1409                     int frame_high)
1410 {
1411   return PY_BT_NO_FILTERS;
1412 }
1413
1414 #endif /* HAVE_PYTHON */
1415
1416 \f
1417
1418 /* Lists for 'set python' commands.  */
1419
1420 static struct cmd_list_element *user_set_python_list;
1421 static struct cmd_list_element *user_show_python_list;
1422
1423 /* Function for use by 'set python' prefix command.  */
1424
1425 static void
1426 user_set_python (char *args, int from_tty)
1427 {
1428   help_list (user_set_python_list, "set python ", all_commands,
1429              gdb_stdout);
1430 }
1431
1432 /* Function for use by 'show python' prefix command.  */
1433
1434 static void
1435 user_show_python (char *args, int from_tty)
1436 {
1437   cmd_show_list (user_show_python_list, from_tty, "");
1438 }
1439
1440 /* Initialize the Python code.  */
1441
1442 #ifdef HAVE_PYTHON
1443
1444 /* This is installed as a final cleanup and cleans up the
1445    interpreter.  This lets Python's 'atexit' work.  */
1446
1447 static void
1448 finalize_python (void *ignore)
1449 {
1450   /* We don't use ensure_python_env here because if we ever ran the
1451      cleanup, gdb would crash -- because the cleanup calls into the
1452      Python interpreter, which we are about to destroy.  It seems
1453      clearer to make the needed calls explicitly here than to create a
1454      cleanup and then mysteriously discard it.  */
1455   (void) PyGILState_Ensure ();
1456   python_gdbarch = target_gdbarch ();
1457   python_language = current_language;
1458
1459   Py_Finalize ();
1460 }
1461 #endif
1462
1463 /* Provide a prototype to silence -Wmissing-prototypes.  */
1464 extern initialize_file_ftype _initialize_python;
1465
1466 void
1467 _initialize_python (void)
1468 {
1469   char *progname;
1470 #ifdef IS_PY3K
1471   int i;
1472   size_t progsize, count;
1473   char *oldloc;
1474   wchar_t *progname_copy;
1475 #endif
1476
1477   add_com ("python-interactive", class_obscure,
1478            python_interactive_command,
1479 #ifdef HAVE_PYTHON
1480            _("\
1481 Start an interactive Python prompt.\n\
1482 \n\
1483 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1484 prompt).\n\
1485 \n\
1486 Alternatively, a single-line Python command can be given as an\n\
1487 argument, and if the command is an expression, the result will be\n\
1488 printed.  For example:\n\
1489 \n\
1490     (gdb) python-interactive 2 + 3\n\
1491     5\n\
1492 ")
1493 #else /* HAVE_PYTHON */
1494            _("\
1495 Start a Python interactive prompt.\n\
1496 \n\
1497 Python scripting is not supported in this copy of GDB.\n\
1498 This command is only a placeholder.")
1499 #endif /* HAVE_PYTHON */
1500            );
1501   add_com_alias ("pi", "python-interactive", class_obscure, 1);
1502
1503   add_com ("python", class_obscure, python_command,
1504 #ifdef HAVE_PYTHON
1505            _("\
1506 Evaluate a Python command.\n\
1507 \n\
1508 The command can be given as an argument, for instance:\n\
1509 \n\
1510     python print 23\n\
1511 \n\
1512 If no argument is given, the following lines are read and used\n\
1513 as the Python commands.  Type a line containing \"end\" to indicate\n\
1514 the end of the command.")
1515 #else /* HAVE_PYTHON */
1516            _("\
1517 Evaluate a Python command.\n\
1518 \n\
1519 Python scripting is not supported in this copy of GDB.\n\
1520 This command is only a placeholder.")
1521 #endif /* HAVE_PYTHON */
1522            );
1523   add_com_alias ("py", "python", class_obscure, 1);
1524
1525   /* Add set/show python print-stack.  */
1526   add_prefix_cmd ("python", no_class, user_show_python,
1527                   _("Prefix command for python preference settings."),
1528                   &user_show_python_list, "show python ", 0,
1529                   &showlist);
1530
1531   add_prefix_cmd ("python", no_class, user_set_python,
1532                   _("Prefix command for python preference settings."),
1533                   &user_set_python_list, "set python ", 0,
1534                   &setlist);
1535
1536   add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
1537                         &gdbpy_should_print_stack, _("\
1538 Set mode for Python stack dump on error."), _("\
1539 Show the mode of Python stack printing on error."), _("\
1540 none  == no stack or message will be printed.\n\
1541 full == a message and a stack will be printed.\n\
1542 message == an error message without a stack will be printed."),
1543                         NULL, NULL,
1544                         &user_set_python_list,
1545                         &user_show_python_list);
1546
1547 #ifdef HAVE_PYTHON
1548 #ifdef WITH_PYTHON_PATH
1549   /* Work around problem where python gets confused about where it is,
1550      and then can't find its libraries, etc.
1551      NOTE: Python assumes the following layout:
1552      /foo/bin/python
1553      /foo/lib/pythonX.Y/...
1554      This must be done before calling Py_Initialize.  */
1555   progname = concat (ldirname (python_libdir), SLASH_STRING, "bin",
1556                      SLASH_STRING, "python", NULL);
1557 #ifdef IS_PY3K
1558   oldloc = setlocale (LC_ALL, NULL);
1559   setlocale (LC_ALL, "");
1560   progsize = strlen (progname);
1561   if (progsize == (size_t) -1)
1562     {
1563       fprintf (stderr, "Could not convert python path to string\n");
1564       return;
1565     }
1566   progname_copy = PyMem_Malloc ((progsize + 1) * sizeof (wchar_t));
1567   if (!progname_copy)
1568     {
1569       fprintf (stderr, "out of memory\n");
1570       return;
1571     }
1572   count = mbstowcs (progname_copy, progname, progsize + 1);
1573   if (count == (size_t) -1)
1574     {
1575       fprintf (stderr, "Could not convert python path to string\n");
1576       return;
1577     }
1578   setlocale (LC_ALL, oldloc);
1579
1580   /* Note that Py_SetProgramName expects the string it is passed to
1581      remain alive for the duration of the program's execution, so
1582      it is not freed after this call.  */
1583   Py_SetProgramName (progname_copy);
1584 #else
1585   Py_SetProgramName (progname);
1586 #endif
1587 #endif
1588
1589   Py_Initialize ();
1590   PyEval_InitThreads ();
1591
1592 #ifdef IS_PY3K
1593   gdb_module = PyModule_Create (&GdbModuleDef);
1594   /* Add _gdb module to the list of known built-in modules.  */
1595   _PyImport_FixupBuiltin (gdb_module, "_gdb");
1596 #else
1597   gdb_module = Py_InitModule ("_gdb", GdbMethods);
1598 #endif
1599   if (gdb_module == NULL)
1600     goto fail;
1601
1602   /* The casts to (char*) are for python 2.4.  */
1603   if (PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version) < 0
1604       || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG",
1605                                      (char*) host_name) < 0
1606       || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1607                                      (char*) target_name) < 0)
1608     goto fail;
1609
1610   /* Add stream constants.  */
1611   if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
1612       || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
1613       || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
1614     goto fail;
1615
1616   gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1617   if (gdbpy_gdb_error == NULL
1618       || PyModule_AddObject (gdb_module, "error", gdbpy_gdb_error) < 0)
1619     goto fail;
1620
1621   gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1622                                                gdbpy_gdb_error, NULL);
1623   if (gdbpy_gdb_memory_error == NULL
1624       || PyModule_AddObject (gdb_module, "MemoryError",
1625                              gdbpy_gdb_memory_error) < 0)
1626     goto fail;
1627
1628   gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1629   if (gdbpy_gdberror_exc == NULL
1630       || PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc) < 0)
1631     goto fail;
1632
1633   gdbpy_initialize_gdb_readline ();
1634
1635   if (gdbpy_initialize_auto_load () < 0
1636       || gdbpy_initialize_values () < 0
1637       || gdbpy_initialize_frames () < 0
1638       || gdbpy_initialize_commands () < 0
1639       || gdbpy_initialize_symbols () < 0
1640       || gdbpy_initialize_symtabs () < 0
1641       || gdbpy_initialize_blocks () < 0
1642       || gdbpy_initialize_functions () < 0
1643       || gdbpy_initialize_parameters () < 0
1644       || gdbpy_initialize_types () < 0
1645       || gdbpy_initialize_pspace () < 0
1646       || gdbpy_initialize_objfile () < 0
1647       || gdbpy_initialize_breakpoints () < 0
1648       || gdbpy_initialize_finishbreakpoints () < 0
1649       || gdbpy_initialize_lazy_string () < 0
1650       || gdbpy_initialize_thread () < 0
1651       || gdbpy_initialize_inferior () < 0
1652       || gdbpy_initialize_events () < 0
1653       || gdbpy_initialize_eventregistry () < 0
1654       || gdbpy_initialize_py_events () < 0
1655       || gdbpy_initialize_event () < 0
1656       || gdbpy_initialize_stop_event () < 0
1657       || gdbpy_initialize_signal_event () < 0
1658       || gdbpy_initialize_breakpoint_event () < 0
1659       || gdbpy_initialize_continue_event () < 0
1660       || gdbpy_initialize_exited_event () < 0
1661       || gdbpy_initialize_thread_event () < 0
1662       || gdbpy_initialize_new_objfile_event ()  < 0
1663       || gdbpy_initialize_arch () < 0)
1664     goto fail;
1665
1666   observer_attach_before_prompt (before_prompt_hook);
1667
1668   gdbpy_to_string_cst = PyString_FromString ("to_string");
1669   if (gdbpy_to_string_cst == NULL)
1670     goto fail;
1671   gdbpy_children_cst = PyString_FromString ("children");
1672   if (gdbpy_children_cst == NULL)
1673     goto fail;
1674   gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1675   if (gdbpy_display_hint_cst == NULL)
1676     goto fail;
1677   gdbpy_doc_cst = PyString_FromString ("__doc__");
1678   if (gdbpy_doc_cst == NULL)
1679     goto fail;
1680   gdbpy_enabled_cst = PyString_FromString ("enabled");
1681   if (gdbpy_enabled_cst == NULL)
1682     goto fail;
1683   gdbpy_value_cst = PyString_FromString ("value");
1684   if (gdbpy_value_cst == NULL)
1685     goto fail;
1686
1687   /* Release the GIL while gdb runs.  */
1688   PyThreadState_Swap (NULL);
1689   PyEval_ReleaseLock ();
1690
1691   make_final_cleanup (finalize_python, NULL);
1692
1693   gdb_python_initialized = 1;
1694   return;
1695
1696  fail:
1697   gdbpy_print_stack ();
1698   /* Do not set 'gdb_python_initialized'.  */
1699   return;
1700
1701 #endif /* HAVE_PYTHON */
1702 }
1703
1704 #ifdef HAVE_PYTHON
1705
1706 /* Perform the remaining python initializations.
1707    These must be done after GDB is at least mostly initialized.
1708    E.g., The "info pretty-printer" command needs the "info" prefix
1709    command installed.  */
1710
1711 void
1712 finish_python_initialization (void)
1713 {
1714   PyObject *m;
1715   char *gdb_pythondir;
1716   PyObject *sys_path;
1717   struct cleanup *cleanup;
1718
1719   cleanup = ensure_python_env (get_current_arch (), current_language);
1720
1721   /* Add the initial data-directory to sys.path.  */
1722
1723   gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
1724   make_cleanup (xfree, gdb_pythondir);
1725
1726   sys_path = PySys_GetObject ("path");
1727
1728   /* If sys.path is not defined yet, define it first.  */
1729   if (!(sys_path && PyList_Check (sys_path)))
1730     {
1731 #ifdef IS_PY3K
1732       PySys_SetPath (L"");
1733 #else
1734       PySys_SetPath ("");
1735 #endif
1736       sys_path = PySys_GetObject ("path");
1737     }
1738   if (sys_path && PyList_Check (sys_path))  
1739     {
1740       PyObject *pythondir;
1741       int err;
1742
1743       pythondir = PyString_FromString (gdb_pythondir);
1744       if (pythondir == NULL)
1745         goto fail;
1746
1747       err = PyList_Insert (sys_path, 0, pythondir);
1748       if (err)
1749         goto fail;
1750
1751       Py_DECREF (pythondir);
1752     }
1753   else
1754     goto fail;
1755
1756   /* Import the gdb module to finish the initialization, and
1757      add it to __main__ for convenience.  */
1758   m = PyImport_AddModule ("__main__");
1759   if (m == NULL)
1760     goto fail;
1761
1762   gdb_python_module = PyImport_ImportModule ("gdb");
1763   if (gdb_python_module == NULL)
1764     {
1765       gdbpy_print_stack ();
1766       /* This is passed in one call to warning so that blank lines aren't
1767          inserted between each line of text.  */
1768       warning (_("\n"
1769                  "Could not load the Python gdb module from `%s'.\n"
1770                  "Limited Python support is available from the _gdb module.\n"
1771                  "Suggest passing --data-directory=/path/to/gdb/data-directory.\n"),
1772                  gdb_pythondir);
1773       do_cleanups (cleanup);
1774       return;
1775     }
1776
1777   if (PyModule_AddObject (m, "gdb", gdb_python_module))
1778     goto fail;
1779
1780   /* Keep the reference to gdb_python_module since it is in a global
1781      variable.  */
1782
1783   do_cleanups (cleanup);
1784   return;
1785
1786  fail:
1787   gdbpy_print_stack ();
1788   warning (_("internal error: Unhandled Python exception"));
1789   do_cleanups (cleanup);
1790 }
1791
1792 #endif /* HAVE_PYTHON */
1793
1794 \f
1795
1796 #ifdef HAVE_PYTHON
1797
1798 static PyMethodDef GdbMethods[] =
1799 {
1800   { "history", gdbpy_history, METH_VARARGS,
1801     "Get a value from history" },
1802   { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1803     "Execute a gdb command" },
1804   { "parameter", gdbpy_parameter, METH_VARARGS,
1805     "Return a gdb parameter's value" },
1806
1807   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1808     "Return a tuple of all breakpoint objects" },
1809
1810   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1811     "Find the default visualizer for a Value." },
1812
1813   { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1814     "Return the current Progspace." },
1815   { "progspaces", gdbpy_progspaces, METH_NOARGS,
1816     "Return a sequence of all progspaces." },
1817
1818   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1819     "Return the current Objfile being loaded, or None." },
1820   { "objfiles", gdbpy_objfiles, METH_NOARGS,
1821     "Return a sequence of all loaded objfiles." },
1822
1823   { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
1824     "newest_frame () -> gdb.Frame.\n\
1825 Return the newest frame object." },
1826   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1827     "selected_frame () -> gdb.Frame.\n\
1828 Return the selected frame object." },
1829   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1830     "stop_reason_string (Integer) -> String.\n\
1831 Return a string explaining unwind stop reason." },
1832
1833   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1834     METH_VARARGS | METH_KEYWORDS,
1835     "lookup_type (name [, block]) -> type\n\
1836 Return a Type corresponding to the given name." },
1837   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1838     METH_VARARGS | METH_KEYWORDS,
1839     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1840 Return a tuple with the symbol corresponding to the given name (or None) and\n\
1841 a boolean indicating if name is a field of the current implied argument\n\
1842 `this' (when the current language is object-oriented)." },
1843   { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
1844     METH_VARARGS | METH_KEYWORDS,
1845     "lookup_global_symbol (name [, domain]) -> symbol\n\
1846 Return the symbol corresponding to the given name (or None)." },
1847   { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1848     "Return the block containing the given pc value, or None." },
1849   { "solib_name", gdbpy_solib_name, METH_VARARGS,
1850     "solib_name (Long) -> String.\n\
1851 Return the name of the shared library holding a given address, or None." },
1852   { "decode_line", gdbpy_decode_line, METH_VARARGS,
1853     "decode_line (String) -> Tuple.  Decode a string argument the way\n\
1854 that 'break' or 'edit' does.  Return a tuple containing two elements.\n\
1855 The first element contains any unparsed portion of the String parameter\n\
1856 (or None if the string was fully parsed).  The second element contains\n\
1857 a tuple that contains all the locations that match, represented as\n\
1858 gdb.Symtab_and_line objects (or None)."},
1859   { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1860     "parse_and_eval (String) -> Value.\n\
1861 Parse String as an expression, evaluate it, and return the result as a Value."
1862   },
1863   { "find_pc_line", gdbpy_find_pc_line, METH_VARARGS,
1864     "find_pc_line (pc) -> Symtab_and_line.\n\
1865 Return the gdb.Symtab_and_line object corresponding to the pc value." },
1866
1867   { "post_event", gdbpy_post_event, METH_VARARGS,
1868     "Post an event into gdb's event loop." },
1869
1870   { "target_charset", gdbpy_target_charset, METH_NOARGS,
1871     "target_charset () -> string.\n\
1872 Return the name of the current target charset." },
1873   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1874     "target_wide_charset () -> string.\n\
1875 Return the name of the current target wide charset." },
1876
1877   { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1878     "string_to_argv (String) -> Array.\n\
1879 Parse String and return an argv-like array.\n\
1880 Arguments are separate by spaces and may be quoted."
1881   },
1882   { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
1883     "Write a string using gdb's filtered stream." },
1884   { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
1885     "Flush gdb's filtered stdout stream." },
1886   { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1887     "selected_thread () -> gdb.InferiorThread.\n\
1888 Return the selected thread object." },
1889   { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
1890     "selected_inferior () -> gdb.Inferior.\n\
1891 Return the selected inferior object." },
1892   { "inferiors", gdbpy_inferiors, METH_NOARGS,
1893     "inferiors () -> (gdb.Inferior, ...).\n\
1894 Return a tuple containing all inferiors." },
1895   {NULL, NULL, 0, NULL}
1896 };
1897
1898 #ifdef IS_PY3K
1899 static struct PyModuleDef GdbModuleDef =
1900 {
1901   PyModuleDef_HEAD_INIT,
1902   "_gdb",
1903   NULL,
1904   -1, 
1905   GdbMethods,
1906   NULL,
1907   NULL,
1908   NULL,
1909   NULL
1910 };
1911 #endif
1912 #endif /* HAVE_PYTHON */