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