gdb/python/python.c - gdb

Global variables defined

Data types defined

Functions defined

Source code

  1. /* General python/gdb code

  2.    Copyright (C) 2008-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "arch-utils.h"
  16. #include "command.h"
  17. #include "ui-out.h"
  18. #include "cli/cli-script.h"
  19. #include "gdbcmd.h"
  20. #include "progspace.h"
  21. #include "objfiles.h"
  22. #include "value.h"
  23. #include "language.h"
  24. #include "event-loop.h"
  25. #include "serial.h"
  26. #include "readline/tilde.h"
  27. #include "python.h"
  28. #include "extension-priv.h"
  29. #include "cli/cli-utils.h"
  30. #include <ctype.h>

  31. /* Declared constants and enum for python stack printing.  */
  32. static const char python_excp_none[] = "none";
  33. static const char python_excp_full[] = "full";
  34. static const char python_excp_message[] = "message";

  35. /* "set python print-stack" choices.  */
  36. static const char *const python_excp_enums[] =
  37.   {
  38.     python_excp_none,
  39.     python_excp_full,
  40.     python_excp_message,
  41.     NULL
  42.   };

  43. /* The exception printing variable.  'full' if we want to print the
  44.    error message and stack, 'none' if we want to print nothing, and
  45.    'message' if we only want to print the error message.  'message' is
  46.    the default.  */
  47. static const char *gdbpy_should_print_stack = python_excp_message;

  48. #ifdef HAVE_PYTHON
  49. /* Forward decls, these are defined later.  */
  50. static const struct extension_language_script_ops python_extension_script_ops;
  51. static const struct extension_language_ops python_extension_ops;
  52. #endif

  53. /* The main struct describing GDB's interface to the Python
  54.    extension language.  */
  55. const struct extension_language_defn extension_language_python =
  56. {
  57.   EXT_LANG_PYTHON,
  58.   "python",
  59.   "Python",

  60.   ".py",
  61.   "-gdb.py",

  62.   python_control,

  63. #ifdef HAVE_PYTHON
  64.   &python_extension_script_ops,
  65.   &python_extension_ops
  66. #else
  67.   NULL,
  68.   NULL
  69. #endif
  70. };

  71. #ifdef HAVE_PYTHON

  72. #include "cli/cli-decode.h"
  73. #include "charset.h"
  74. #include "top.h"
  75. #include "solib.h"
  76. #include "python-internal.h"
  77. #include "linespec.h"
  78. #include "source.h"
  79. #include "version.h"
  80. #include "target.h"
  81. #include "gdbthread.h"
  82. #include "interps.h"
  83. #include "event-top.h"

  84. /* True if Python has been successfully initialized, false
  85.    otherwise.  */

  86. int gdb_python_initialized;

  87. static PyMethodDef GdbMethods[];

  88. #ifdef IS_PY3K
  89. static struct PyModuleDef GdbModuleDef;
  90. #endif

  91. PyObject *gdb_module;
  92. PyObject *gdb_python_module;

  93. /* Some string constants we may wish to use.  */
  94. PyObject *gdbpy_to_string_cst;
  95. PyObject *gdbpy_children_cst;
  96. PyObject *gdbpy_display_hint_cst;
  97. PyObject *gdbpy_doc_cst;
  98. PyObject *gdbpy_enabled_cst;
  99. PyObject *gdbpy_value_cst;

  100. /* The GdbError exception.  */
  101. PyObject *gdbpy_gdberror_exc;

  102. /* The `gdb.error' base class.  */
  103. PyObject *gdbpy_gdb_error;

  104. /* The `gdb.MemoryError' exception.  */
  105. PyObject *gdbpy_gdb_memory_error;

  106. static script_sourcer_func gdbpy_source_script;
  107. static objfile_script_sourcer_func gdbpy_source_objfile_script;
  108. static void gdbpy_finish_initialization
  109.   (const struct extension_language_defn *);
  110. static int gdbpy_initialized (const struct extension_language_defn *);
  111. static void gdbpy_eval_from_control_command
  112.   (const struct extension_language_defn *, struct command_line *cmd);
  113. static void gdbpy_start_type_printers (const struct extension_language_defn *,
  114.                                        struct ext_lang_type_printers *);
  115. static enum ext_lang_rc gdbpy_apply_type_printers
  116.   (const struct extension_language_defn *,
  117.    const struct ext_lang_type_printers *, struct type *, char **);
  118. static void gdbpy_free_type_printers (const struct extension_language_defn *,
  119.                                       struct ext_lang_type_printers *);
  120. static void gdbpy_clear_quit_flag (const struct extension_language_defn *);
  121. static void gdbpy_set_quit_flag (const struct extension_language_defn *);
  122. static int gdbpy_check_quit_flag (const struct extension_language_defn *);
  123. static enum ext_lang_rc gdbpy_before_prompt_hook
  124.   (const struct extension_language_defn *, const char *current_gdb_prompt);

  125. /* The interface between gdb proper and loading of python scripts.  */

  126. static const struct extension_language_script_ops python_extension_script_ops =
  127. {
  128.   gdbpy_source_script,
  129.   gdbpy_source_objfile_script,
  130.   gdbpy_auto_load_enabled
  131. };

  132. /* The interface between gdb proper and python extensions.  */

  133. static const struct extension_language_ops python_extension_ops =
  134. {
  135.   gdbpy_finish_initialization,
  136.   gdbpy_initialized,

  137.   gdbpy_eval_from_control_command,

  138.   gdbpy_start_type_printers,
  139.   gdbpy_apply_type_printers,
  140.   gdbpy_free_type_printers,

  141.   gdbpy_apply_val_pretty_printer,

  142.   gdbpy_apply_frame_filter,

  143.   gdbpy_preserve_values,

  144.   gdbpy_breakpoint_has_cond,
  145.   gdbpy_breakpoint_cond_says_stop,

  146.   gdbpy_clear_quit_flag,
  147.   gdbpy_set_quit_flag,
  148.   gdbpy_check_quit_flag,

  149.   gdbpy_before_prompt_hook,

  150.   gdbpy_clone_xmethod_worker_data,
  151.   gdbpy_free_xmethod_worker_data,
  152.   gdbpy_get_matching_xmethod_workers,
  153.   gdbpy_get_xmethod_arg_types,
  154.   gdbpy_invoke_xmethod
  155. };

  156. /* Architecture and language to be used in callbacks from
  157.    the Python interpreter.  */
  158. struct gdbarch *python_gdbarch;
  159. const struct language_defn *python_language;

  160. /* Restore global language and architecture and Python GIL state
  161.    when leaving the Python interpreter.  */

  162. struct python_env
  163. {
  164.   struct active_ext_lang_state *previous_active;
  165.   PyGILState_STATE state;
  166.   struct gdbarch *gdbarch;
  167.   const struct language_defn *language;
  168.   PyObject *error_type, *error_value, *error_traceback;
  169. };

  170. static void
  171. restore_python_env (void *p)
  172. {
  173.   struct python_env *env = (struct python_env *)p;

  174.   /* Leftover Python error is forbidden by Python Exception Handling.  */
  175.   if (PyErr_Occurred ())
  176.     {
  177.       /* This order is similar to the one calling error afterwards. */
  178.       gdbpy_print_stack ();
  179.       warning (_("internal error: Unhandled Python exception"));
  180.     }

  181.   PyErr_Restore (env->error_type, env->error_value, env->error_traceback);

  182.   PyGILState_Release (env->state);
  183.   python_gdbarch = env->gdbarch;
  184.   python_language = env->language;

  185.   restore_active_ext_lang (env->previous_active);

  186.   xfree (env);
  187. }

  188. /* Called before entering the Python interpreter to install the
  189.    current language and architecture to be used for Python values.
  190.    Also set the active extension language for GDB so that SIGINT's
  191.    are directed our way, and if necessary install the right SIGINT
  192.    handler.  */

  193. struct cleanup *
  194. ensure_python_env (struct gdbarch *gdbarch,
  195.                    const struct language_defn *language)
  196. {
  197.   struct python_env *env = xmalloc (sizeof *env);

  198.   /* We should not ever enter Python unless initialized.  */
  199.   if (!gdb_python_initialized)
  200.     error (_("Python not initialized"));

  201.   env->previous_active = set_active_ext_lang (&extension_language_python);

  202.   env->state = PyGILState_Ensure ();
  203.   env->gdbarch = python_gdbarch;
  204.   env->language = python_language;

  205.   python_gdbarch = gdbarch;
  206.   python_language = language;

  207.   /* Save it and ensure ! PyErr_Occurred () afterwards.  */
  208.   PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);

  209.   return make_cleanup (restore_python_env, env);
  210. }

  211. /* Clear the quit flag.  */

  212. static void
  213. gdbpy_clear_quit_flag (const struct extension_language_defn *extlang)
  214. {
  215.   /* This clears the flag as a side effect.  */
  216.   PyOS_InterruptOccurred ();
  217. }

  218. /* Set the quit flag.  */

  219. static void
  220. gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
  221. {
  222.   PyErr_SetInterrupt ();
  223. }

  224. /* Return true if the quit flag has been set, false otherwise.  */

  225. static int
  226. gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
  227. {
  228.   return PyOS_InterruptOccurred ();
  229. }

  230. /* Evaluate a Python command like PyRun_SimpleString, but uses
  231.    Py_single_input which prints the result of expressions, and does
  232.    not automatically print the stack on errors.  */

  233. static int
  234. eval_python_command (const char *command)
  235. {
  236.   PyObject *m, *d, *v;

  237.   m = PyImport_AddModule ("__main__");
  238.   if (m == NULL)
  239.     return -1;

  240.   d = PyModule_GetDict (m);
  241.   if (d == NULL)
  242.     return -1;
  243.   v = PyRun_StringFlags (command, Py_single_input, d, d, NULL);
  244.   if (v == NULL)
  245.     return -1;

  246.   Py_DECREF (v);
  247. #ifndef IS_PY3K
  248.   if (Py_FlushLine ())
  249.     PyErr_Clear ();
  250. #endif

  251.   return 0;
  252. }

  253. /* Implementation of the gdb "python-interactive" command.  */

  254. static void
  255. python_interactive_command (char *arg, int from_tty)
  256. {
  257.   struct cleanup *cleanup;
  258.   int err;

  259.   cleanup = make_cleanup_restore_integer (&interpreter_async);
  260.   interpreter_async = 0;

  261.   arg = skip_spaces (arg);

  262.   ensure_python_env (get_current_arch (), current_language);

  263.   if (arg && *arg)
  264.     {
  265.       int len = strlen (arg);
  266.       char *script = xmalloc (len + 2);

  267.       strcpy (script, arg);
  268.       script[len] = '\n';
  269.       script[len + 1] = '\0';
  270.       err = eval_python_command (script);
  271.       xfree (script);
  272.     }
  273.   else
  274.     {
  275.       err = PyRun_InteractiveLoop (instream, "<stdin>");
  276.       dont_repeat ();
  277.     }

  278.   if (err)
  279.     {
  280.       gdbpy_print_stack ();
  281.       error (_("Error while executing Python code."));
  282.     }

  283.   do_cleanups (cleanup);
  284. }

  285. /* A wrapper around PyRun_SimpleFile.  FILE is the Python script to run
  286.    named FILENAME.

  287.    On Windows hosts few users would build Python themselves (this is no
  288.    trivial task on this platform), and thus use binaries built by
  289.    someone else instead.  There may happen situation where the Python
  290.    library and GDB are using two different versions of the C runtime
  291.    library.  Python, being built with VC, would use one version of the
  292.    msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
  293.    A FILE * from one runtime does not necessarily operate correctly in
  294.    the other runtime.

  295.    To work around this potential issue, we create on Windows hosts the
  296.    FILE object using Python routines, thus making sure that it is
  297.    compatible with the Python library.  */

  298. static void
  299. python_run_simple_file (FILE *file, const char *filename)
  300. {
  301. #ifndef _WIN32

  302.   PyRun_SimpleFile (file, filename);

  303. #else /* _WIN32 */

  304.   char *full_path;
  305.   PyObject *python_file;
  306.   struct cleanup *cleanup;

  307.   /* Because we have a string for a filename, and are using Python to
  308.      open the file, we need to expand any tilde in the path first.  */
  309.   full_path = tilde_expand (filename);
  310.   cleanup = make_cleanup (xfree, full_path);
  311.   python_file = PyFile_FromString (full_path, "r");
  312.   if (! python_file)
  313.     {
  314.       do_cleanups (cleanup);
  315.       gdbpy_print_stack ();
  316.       error (_("Error while opening file: %s"), full_path);
  317.     }

  318.   make_cleanup_py_decref (python_file);
  319.   PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
  320.   do_cleanups (cleanup);

  321. #endif /* _WIN32 */
  322. }

  323. /* Given a command_line, return a command string suitable for passing
  324.    to Python.  Lines in the string are separated by newlines.  The
  325.    return value is allocated using xmalloc and the caller is
  326.    responsible for freeing it.  */

  327. static char *
  328. compute_python_string (struct command_line *l)
  329. {
  330.   struct command_line *iter;
  331.   char *script = NULL;
  332.   int size = 0;
  333.   int here;

  334.   for (iter = l; iter; iter = iter->next)
  335.     size += strlen (iter->line) + 1;

  336.   script = xmalloc (size + 1);
  337.   here = 0;
  338.   for (iter = l; iter; iter = iter->next)
  339.     {
  340.       int len = strlen (iter->line);

  341.       strcpy (&script[here], iter->line);
  342.       here += len;
  343.       script[here++] = '\n';
  344.     }
  345.   script[here] = '\0';
  346.   return script;
  347. }

  348. /* Take a command line structure representing a 'python' command, and
  349.    evaluate its body using the Python interpreter.  */

  350. static void
  351. gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
  352.                                  struct command_line *cmd)
  353. {
  354.   int ret;
  355.   char *script;
  356.   struct cleanup *cleanup;

  357.   if (cmd->body_count != 1)
  358.     error (_("Invalid \"python\" block structure."));

  359.   cleanup = ensure_python_env (get_current_arch (), current_language);

  360.   script = compute_python_string (cmd->body_list[0]);
  361.   ret = PyRun_SimpleString (script);
  362.   xfree (script);
  363.   if (ret)
  364.     error (_("Error while executing Python code."));

  365.   do_cleanups (cleanup);
  366. }

  367. /* Implementation of the gdb "python" command.  */

  368. static void
  369. python_command (char *arg, int from_tty)
  370. {
  371.   struct cleanup *cleanup;

  372.   cleanup = ensure_python_env (get_current_arch (), current_language);

  373.   make_cleanup_restore_integer (&interpreter_async);
  374.   interpreter_async = 0;

  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.       make_cleanup_free_command_lines (&l);
  385.       execute_control_command_untraced (l);
  386.     }

  387.   do_cleanups (cleanup);
  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.         if (! str)
  405.           str = "";
  406.         return PyString_Decode (str, strlen (str), host_charset (), NULL);
  407.       }

  408.     case var_boolean:
  409.       {
  410.         if (* (int *) var)
  411.           Py_RETURN_TRUE;
  412.         else
  413.           Py_RETURN_FALSE;
  414.       }

  415.     case var_auto_boolean:
  416.       {
  417.         enum auto_boolean ab = * (enum auto_boolean *) var;

  418.         if (ab == AUTO_BOOLEAN_TRUE)
  419.           Py_RETURN_TRUE;
  420.         else if (ab == AUTO_BOOLEAN_FALSE)
  421.           Py_RETURN_FALSE;
  422.         else
  423.           Py_RETURN_NONE;
  424.       }

  425.     case var_integer:
  426.       if ((* (int *) var) == INT_MAX)
  427.         Py_RETURN_NONE;
  428.       /* Fall through.  */
  429.     case var_zinteger:
  430.       return PyLong_FromLong (* (int *) var);

  431.     case var_uinteger:
  432.       {
  433.         unsigned int val = * (unsigned int *) var;

  434.         if (val == UINT_MAX)
  435.           Py_RETURN_NONE;
  436.         return PyLong_FromUnsignedLong (val);
  437.       }
  438.     }

  439.   return PyErr_Format (PyExc_RuntimeError,
  440.                        _("Programmer error: unhandled type."));
  441. }

  442. /* A Python function which returns a gdb parameter's value as a Python
  443.    value.  */

  444. PyObject *
  445. gdbpy_parameter (PyObject *self, PyObject *args)
  446. {
  447.   struct cmd_list_element *alias, *prefix, *cmd;
  448.   const char *arg;
  449.   char *newarg;
  450.   int found = -1;
  451.   volatile struct gdb_exception except;

  452.   if (! PyArg_ParseTuple (args, "s", &arg))
  453.     return NULL;

  454.   newarg = concat ("show ", arg, (char *) NULL);

  455.   TRY_CATCH (except, RETURN_MASK_ALL)
  456.     {
  457.       found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
  458.     }
  459.   xfree (newarg);
  460.   GDB_PY_HANDLE_EXCEPTION (except);
  461.   if (!found)
  462.     return PyErr_Format (PyExc_RuntimeError,
  463.                          _("Could not find parameter `%s'."), arg);

  464.   if (! cmd->var)
  465.     return PyErr_Format (PyExc_RuntimeError,
  466.                          _("`%s' is not a parameter."), arg);
  467.   return gdbpy_parameter_value (cmd->var_type, cmd->var);
  468. }

  469. /* Wrapper for target_charset.  */

  470. static PyObject *
  471. gdbpy_target_charset (PyObject *self, PyObject *args)
  472. {
  473.   const char *cset = target_charset (python_gdbarch);

  474.   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
  475. }

  476. /* Wrapper for target_wide_charset.  */

  477. static PyObject *
  478. gdbpy_target_wide_charset (PyObject *self, PyObject *args)
  479. {
  480.   const char *cset = target_wide_charset (python_gdbarch);

  481.   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
  482. }

  483. /* A Python function which evaluates a string using the gdb CLI.  */

  484. static PyObject *
  485. execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
  486. {
  487.   const char *arg;
  488.   PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
  489.   int from_tty, to_string;
  490.   volatile struct gdb_exception except;
  491.   static char *keywords[] = {"command", "from_tty", "to_string", NULL };
  492.   char *result = NULL;

  493.   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
  494.                                      &PyBool_Type, &from_tty_obj,
  495.                                      &PyBool_Type, &to_string_obj))
  496.     return NULL;

  497.   from_tty = 0;
  498.   if (from_tty_obj)
  499.     {
  500.       int cmp = PyObject_IsTrue (from_tty_obj);
  501.       if (cmp < 0)
  502.         return NULL;
  503.       from_tty = cmp;
  504.     }

  505.   to_string = 0;
  506.   if (to_string_obj)
  507.     {
  508.       int cmp = PyObject_IsTrue (to_string_obj);
  509.       if (cmp < 0)
  510.         return NULL;
  511.       to_string = cmp;
  512.     }

  513.   TRY_CATCH (except, RETURN_MASK_ALL)
  514.     {
  515.       /* Copy the argument text in case the command modifies it.  */
  516.       char *copy = xstrdup (arg);
  517.       struct cleanup *cleanup = make_cleanup (xfree, copy);

  518.       make_cleanup_restore_integer (&interpreter_async);
  519.       interpreter_async = 0;

  520.       prevent_dont_repeat ();
  521.       if (to_string)
  522.         result = execute_command_to_string (copy, from_tty);
  523.       else
  524.         {
  525.           result = NULL;
  526.           execute_command (copy, from_tty);
  527.         }

  528.       do_cleanups (cleanup);
  529.     }
  530.   GDB_PY_HANDLE_EXCEPTION (except);

  531.   /* Do any commands attached to breakpoint we stopped at.  */
  532.   bpstat_do_actions ();

  533.   if (result)
  534.     {
  535.       PyObject *r = PyString_FromString (result);
  536.       xfree (result);
  537.       return r;
  538.     }
  539.   Py_RETURN_NONE;
  540. }

  541. /* Implementation of gdb.solib_name (Long) -> String.
  542.    Returns the name of the shared library holding a given address, or None.  */

  543. static PyObject *
  544. gdbpy_solib_name (PyObject *self, PyObject *args)
  545. {
  546.   char *soname;
  547.   PyObject *str_obj;
  548.   gdb_py_longest pc;

  549.   if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
  550.     return NULL;

  551.   soname = solib_name_from_address (current_program_space, pc);
  552.   if (soname)
  553.     str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
  554.   else
  555.     {
  556.       str_obj = Py_None;
  557.       Py_INCREF (Py_None);
  558.     }

  559.   return str_obj;
  560. }

  561. /* A Python function which is a wrapper for decode_line_1.  */

  562. static PyObject *
  563. gdbpy_decode_line (PyObject *self, PyObject *args)
  564. {
  565.   struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
  566.                                                   appease gcc.  */
  567.   struct symtab_and_line sal;
  568.   const char *arg = NULL;
  569.   char *copy_to_free = NULL, *copy = NULL;
  570.   struct cleanup *cleanups;
  571.   PyObject *result = NULL;
  572.   PyObject *return_result = NULL;
  573.   PyObject *unparsed = NULL;
  574.   volatile struct gdb_exception except;

  575.   if (! PyArg_ParseTuple (args, "|s", &arg))
  576.     return NULL;

  577.   cleanups = make_cleanup (null_cleanup, NULL);

  578.   sals.sals = NULL;
  579.   TRY_CATCH (except, RETURN_MASK_ALL)
  580.     {
  581.       if (arg)
  582.         {
  583.           copy = xstrdup (arg);
  584.           copy_to_free = copy;
  585.           sals = decode_line_1 (&copy, 0, 0, 0);
  586.         }
  587.       else
  588.         {
  589.           set_default_source_symtab_and_line ();
  590.           sal = get_current_source_symtab_and_line ();
  591.           sals.sals = &sal;
  592.           sals.nelts = 1;
  593.         }
  594.     }

  595.   if (sals.sals != NULL && sals.sals != &sal)
  596.     {
  597.       make_cleanup (xfree, copy_to_free);
  598.       make_cleanup (xfree, sals.sals);
  599.     }

  600.   if (except.reason < 0)
  601.     {
  602.       do_cleanups (cleanups);
  603.       /* We know this will always throw.  */
  604.       gdbpy_convert_exception (except);
  605.       return NULL;
  606.     }

  607.   if (sals.nelts)
  608.     {
  609.       int i;

  610.       result = PyTuple_New (sals.nelts);
  611.       if (! result)
  612.         goto error;
  613.       for (i = 0; i < sals.nelts; ++i)
  614.         {
  615.           PyObject *obj;

  616.           obj = symtab_and_line_to_sal_object (sals.sals[i]);
  617.           if (! obj)
  618.             {
  619.               Py_DECREF (result);
  620.               goto error;
  621.             }

  622.           PyTuple_SetItem (result, i, obj);
  623.         }
  624.     }
  625.   else
  626.     {
  627.       result = Py_None;
  628.       Py_INCREF (Py_None);
  629.     }

  630.   return_result = PyTuple_New (2);
  631.   if (! return_result)
  632.     {
  633.       Py_DECREF (result);
  634.       goto error;
  635.     }

  636.   if (copy && strlen (copy) > 0)
  637.     {
  638.       unparsed = PyString_FromString (copy);
  639.       if (unparsed == NULL)
  640.         {
  641.           Py_DECREF (result);
  642.           Py_DECREF (return_result);
  643.           return_result = NULL;
  644.           goto error;
  645.         }
  646.     }
  647.   else
  648.     {
  649.       unparsed = Py_None;
  650.       Py_INCREF (Py_None);
  651.     }

  652.   PyTuple_SetItem (return_result, 0, unparsed);
  653.   PyTuple_SetItem (return_result, 1, result);

  654. error:
  655.   do_cleanups (cleanups);

  656.   return return_result;
  657. }

  658. /* Parse a string and evaluate it as an expression.  */
  659. static PyObject *
  660. gdbpy_parse_and_eval (PyObject *self, PyObject *args)
  661. {
  662.   const char *expr_str;
  663.   struct value *result = NULL;
  664.   volatile struct gdb_exception except;

  665.   if (!PyArg_ParseTuple (args, "s", &expr_str))
  666.     return NULL;

  667.   TRY_CATCH (except, RETURN_MASK_ALL)
  668.     {
  669.       result = parse_and_eval (expr_str);
  670.     }
  671.   GDB_PY_HANDLE_EXCEPTION (except);

  672.   return value_to_value_object (result);
  673. }

  674. /* Implementation of gdb.find_pc_line function.
  675.    Returns the gdb.Symtab_and_line object corresponding to a PC value.  */

  676. static PyObject *
  677. gdbpy_find_pc_line (PyObject *self, PyObject *args)
  678. {
  679.   gdb_py_ulongest pc_llu;
  680.   volatile struct gdb_exception except;
  681.   PyObject *result = NULL; /* init for gcc -Wall */

  682.   if (!PyArg_ParseTuple (args, GDB_PY_LLU_ARG, &pc_llu))
  683.     return NULL;

  684.   TRY_CATCH (except, RETURN_MASK_ALL)
  685.     {
  686.       struct symtab_and_line sal;
  687.       CORE_ADDR pc;

  688.       pc = (CORE_ADDR) pc_llu;
  689.       sal = find_pc_line (pc, 0);
  690.       result = symtab_and_line_to_sal_object (sal);
  691.     }
  692.   GDB_PY_HANDLE_EXCEPTION (except);

  693.   return result;
  694. }

  695. /* Read a file as Python code.
  696.    This is the extension_language_script_ops.script_sourcer "method".
  697.    FILE is the file to loadFILENAME is name of the file FILE.
  698.    This does not throw any errors.  If an exception occurs python will print
  699.    the traceback and clear the error indicator.  */

  700. static void
  701. gdbpy_source_script (const struct extension_language_defn *extlang,
  702.                      FILE *file, const char *filename)
  703. {
  704.   struct cleanup *cleanup;

  705.   cleanup = ensure_python_env (get_current_arch (), current_language);
  706.   python_run_simple_file (file, filename);
  707.   do_cleanups (cleanup);
  708. }



  709. /* Posting and handling events.  */

  710. /* A single event.  */
  711. struct gdbpy_event
  712. {
  713.   /* The Python event.  This is just a callable object.  */
  714.   PyObject *event;
  715.   /* The next event.  */
  716.   struct gdbpy_event *next;
  717. };

  718. /* All pending events.  */
  719. static struct gdbpy_event *gdbpy_event_list;
  720. /* The final link of the event list.  */
  721. static struct gdbpy_event **gdbpy_event_list_end;

  722. /* We use a file handler, and not an async handler, so that we can
  723.    wake up the main thread even when it is blocked in poll().  */
  724. static struct serial *gdbpy_event_fds[2];

  725. /* The file handler callback.  This reads from the internal pipe, and
  726.    then processes the Python event queue.  This will always be run in
  727.    the main gdb thread.  */

  728. static void
  729. gdbpy_run_events (struct serial *scb, void *context)
  730. {
  731.   struct cleanup *cleanup;

  732.   cleanup = ensure_python_env (get_current_arch (), current_language);

  733.   /* Flush the fd.  Do this before flushing the events list, so that
  734.      any new event post afterwards is sure to re-awake the event
  735.      loop.  */
  736.   while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
  737.     ;

  738.   while (gdbpy_event_list)
  739.     {
  740.       PyObject *call_result;

  741.       /* Dispatching the event might push a new element onto the event
  742.          loop, so we update here "atomically enough".  */
  743.       struct gdbpy_event *item = gdbpy_event_list;
  744.       gdbpy_event_list = gdbpy_event_list->next;
  745.       if (gdbpy_event_list == NULL)
  746.         gdbpy_event_list_end = &gdbpy_event_list;

  747.       /* Ignore errors.  */
  748.       call_result = PyObject_CallObject (item->event, NULL);
  749.       if (call_result == NULL)
  750.         PyErr_Clear ();

  751.       Py_XDECREF (call_result);
  752.       Py_DECREF (item->event);
  753.       xfree (item);
  754.     }

  755.   do_cleanups (cleanup);
  756. }

  757. /* Submit an event to the gdb thread.  */
  758. static PyObject *
  759. gdbpy_post_event (PyObject *self, PyObject *args)
  760. {
  761.   struct gdbpy_event *event;
  762.   PyObject *func;
  763.   int wakeup;

  764.   if (!PyArg_ParseTuple (args, "O", &func))
  765.     return NULL;

  766.   if (!PyCallable_Check (func))
  767.     {
  768.       PyErr_SetString (PyExc_RuntimeError,
  769.                        _("Posted event is not callable"));
  770.       return NULL;
  771.     }

  772.   Py_INCREF (func);

  773.   /* From here until the end of the function, we have the GIL, so we
  774.      can operate on our global data structures without worrying.  */
  775.   wakeup = gdbpy_event_list == NULL;

  776.   event = XNEW (struct gdbpy_event);
  777.   event->event = func;
  778.   event->next = NULL;
  779.   *gdbpy_event_list_end = event;
  780.   gdbpy_event_list_end = &event->next;

  781.   /* Wake up gdb when needed.  */
  782.   if (wakeup)
  783.     {
  784.       char c = 'q';                /* Anything. */

  785.       if (serial_write (gdbpy_event_fds[1], &c, 1))
  786.         return PyErr_SetFromErrno (PyExc_IOError);
  787.     }

  788.   Py_RETURN_NONE;
  789. }

  790. /* Initialize the Python event handler.  */
  791. static int
  792. gdbpy_initialize_events (void)
  793. {
  794.   if (serial_pipe (gdbpy_event_fds) == 0)
  795.     {
  796.       gdbpy_event_list_end = &gdbpy_event_list;
  797.       serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
  798.     }

  799.   return 0;
  800. }



  801. /* This is the extension_language_ops.before_prompt "method".  */

  802. static enum ext_lang_rc
  803. gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
  804.                           const char *current_gdb_prompt)
  805. {
  806.   struct cleanup *cleanup;
  807.   char *prompt = NULL;

  808.   if (!gdb_python_initialized)
  809.     return EXT_LANG_RC_NOP;

  810.   cleanup = ensure_python_env (get_current_arch (), current_language);

  811.   if (gdb_python_module
  812.       && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
  813.     {
  814.       PyObject *hook;

  815.       hook = PyObject_GetAttrString (gdb_python_module, "prompt_hook");
  816.       if (hook == NULL)
  817.         goto fail;

  818.       make_cleanup_py_decref (hook);

  819.       if (PyCallable_Check (hook))
  820.         {
  821.           PyObject *result;
  822.           PyObject *current_prompt;

  823.           current_prompt = PyString_FromString (current_gdb_prompt);
  824.           if (current_prompt == NULL)
  825.             goto fail;

  826.           result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);

  827.           Py_DECREF (current_prompt);

  828.           if (result == NULL)
  829.             goto fail;

  830.           make_cleanup_py_decref (result);

  831.           /* Return type should be None, or a String.  If it is None,
  832.              fall through, we will not set a prompt.  If it is a
  833.              string, set  PROMPT.  Anything else, set an exception.  */
  834.           if (result != Py_None && ! PyString_Check (result))
  835.             {
  836.               PyErr_Format (PyExc_RuntimeError,
  837.                             _("Return from prompt_hook must " \
  838.                               "be either a Python string, or None"));
  839.               goto fail;
  840.             }

  841.           if (result != Py_None)
  842.             {
  843.               prompt = python_string_to_host_string (result);

  844.               if (prompt == NULL)
  845.                 goto fail;
  846.               else
  847.                 make_cleanup (xfree, prompt);
  848.             }
  849.         }
  850.     }

  851.   /* If a prompt has been set, PROMPT will not be NULL.  If it is
  852.      NULL, do not set the prompt.  */
  853.   if (prompt != NULL)
  854.     set_prompt (prompt);

  855.   do_cleanups (cleanup);
  856.   return prompt != NULL ? EXT_LANG_RC_OK : EXT_LANG_RC_NOP;

  857. fail:
  858.   gdbpy_print_stack ();
  859.   do_cleanups (cleanup);
  860.   return EXT_LANG_RC_ERROR;
  861. }



  862. /* Printing.  */

  863. /* A python function to write a single string using gdb's filtered
  864.    output stream .  The optional keyword STREAM can be used to write
  865.    to a particular stream.  The default stream is to gdb_stdout.  */

  866. static PyObject *
  867. gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
  868. {
  869.   const char *arg;
  870.   static char *keywords[] = {"text", "stream", NULL };
  871.   int stream_type = 0;
  872.   volatile struct gdb_exception except;

  873.   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
  874.                                      &stream_type))
  875.     return NULL;

  876.   TRY_CATCH (except, RETURN_MASK_ALL)
  877.     {
  878.       switch (stream_type)
  879.         {
  880.         case 1:
  881.           {
  882.             fprintf_filtered (gdb_stderr, "%s", arg);
  883.             break;
  884.           }
  885.         case 2:
  886.           {
  887.             fprintf_filtered (gdb_stdlog, "%s", arg);
  888.             break;
  889.           }
  890.         default:
  891.           fprintf_filtered (gdb_stdout, "%s", arg);
  892.         }
  893.     }
  894.   GDB_PY_HANDLE_EXCEPTION (except);

  895.   Py_RETURN_NONE;
  896. }

  897. /* A python function to flush a gdb stream.  The optional keyword
  898.    STREAM can be used to flush a particular stream.  The default stream
  899.    is gdb_stdout.  */

  900. static PyObject *
  901. gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
  902. {
  903.   static char *keywords[] = {"stream", NULL };
  904.   int stream_type = 0;

  905.   if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
  906.                                      &stream_type))
  907.     return NULL;

  908.   switch (stream_type)
  909.     {
  910.     case 1:
  911.       {
  912.         gdb_flush (gdb_stderr);
  913.         break;
  914.       }
  915.     case 2:
  916.       {
  917.         gdb_flush (gdb_stdlog);
  918.         break;
  919.       }
  920.     default:
  921.       gdb_flush (gdb_stdout);
  922.     }

  923.   Py_RETURN_NONE;
  924. }

  925. /* Print a python exception trace, print just a message, or print
  926.    nothing and clear the python exception, depending on
  927.    gdbpy_should_print_stack.  Only call this if a python exception is
  928.    set.  */
  929. void
  930. gdbpy_print_stack (void)
  931. {
  932.   volatile struct gdb_exception except;

  933.   /* Print "none", just clear exception.  */
  934.   if (gdbpy_should_print_stack == python_excp_none)
  935.     {
  936.       PyErr_Clear ();
  937.     }
  938.   /* Print "full" message and backtrace.  */
  939.   else if (gdbpy_should_print_stack == python_excp_full)
  940.     {
  941.       PyErr_Print ();
  942.       /* PyErr_Print doesn't necessarily end output with a newline.
  943.          This works because Python's stdout/stderr is fed through
  944.          printf_filtered.  */
  945.       TRY_CATCH (except, RETURN_MASK_ALL)
  946.         {
  947.           begin_line ();
  948.         }
  949.     }
  950.   /* Print "message", just error print message.  */
  951.   else
  952.     {
  953.       PyObject *ptype, *pvalue, *ptraceback;
  954.       char *msg = NULL, *type = NULL;

  955.       PyErr_Fetch (&ptype, &pvalue, &ptraceback);

  956.       /* Fetch the error message contained within ptype, pvalue.  */
  957.       msg = gdbpy_exception_to_string (ptype, pvalue);
  958.       type = gdbpy_obj_to_string (ptype);

  959.       TRY_CATCH (except, RETURN_MASK_ALL)
  960.         {
  961.           if (msg == NULL)
  962.             {
  963.               /* An error occurred computing the string representation of the
  964.                  error message.  */
  965.               fprintf_filtered (gdb_stderr,
  966.                                 _("Error occurred computing Python error" \
  967.                                   "message.\n"));
  968.             }
  969.           else
  970.             fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
  971.                               type, msg);
  972.         }

  973.       Py_XDECREF (ptype);
  974.       Py_XDECREF (pvalue);
  975.       Py_XDECREF (ptraceback);
  976.       xfree (msg);
  977.     }
  978. }



  979. /* Return the current Progspace.
  980.    There always is one.  */

  981. static PyObject *
  982. gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
  983. {
  984.   PyObject *result;

  985.   result = pspace_to_pspace_object (current_program_space);
  986.   if (result)
  987.     Py_INCREF (result);
  988.   return result;
  989. }

  990. /* Return a sequence holding all the Progspaces.  */

  991. static PyObject *
  992. gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
  993. {
  994.   struct program_space *ps;
  995.   PyObject *list;

  996.   list = PyList_New (0);
  997.   if (!list)
  998.     return NULL;

  999.   ALL_PSPACES (ps)
  1000.   {
  1001.     PyObject *item = pspace_to_pspace_object (ps);

  1002.     if (!item || PyList_Append (list, item) == -1)
  1003.       {
  1004.         Py_DECREF (list);
  1005.         return NULL;
  1006.       }
  1007.   }

  1008.   return list;
  1009. }



  1010. /* The "current" objfile.  This is set when gdb detects that a new
  1011.    objfile has been loaded.  It is only set for the duration of a call to
  1012.    gdbpy_source_objfile_script; it is NULL at other times.  */
  1013. static struct objfile *gdbpy_current_objfile;

  1014. /* Set the current objfile to OBJFILE and then read FILE named FILENAME
  1015.    as Python code.  This does not throw any errors.  If an exception
  1016.    occurs python will print the traceback and clear the error indicator.
  1017.    This is the extension_language_script_ops.objfile_script_sourcer
  1018.    "method".  */

  1019. static void
  1020. gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
  1021.                              struct objfile *objfile, FILE *file,
  1022.                              const char *filename)
  1023. {
  1024.   struct cleanup *cleanups;

  1025.   if (!gdb_python_initialized)
  1026.     return;

  1027.   cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
  1028.   gdbpy_current_objfile = objfile;

  1029.   python_run_simple_file (file, filename);

  1030.   do_cleanups (cleanups);
  1031.   gdbpy_current_objfile = NULL;
  1032. }

  1033. /* Return the current Objfile, or None if there isn't one.  */

  1034. static PyObject *
  1035. gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
  1036. {
  1037.   PyObject *result;

  1038.   if (! gdbpy_current_objfile)
  1039.     Py_RETURN_NONE;

  1040.   result = objfile_to_objfile_object (gdbpy_current_objfile);
  1041.   if (result)
  1042.     Py_INCREF (result);
  1043.   return result;
  1044. }

  1045. /* Return a sequence holding all the Objfiles.  */

  1046. static PyObject *
  1047. gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
  1048. {
  1049.   struct objfile *objf;
  1050.   PyObject *list;

  1051.   list = PyList_New (0);
  1052.   if (!list)
  1053.     return NULL;

  1054.   ALL_OBJFILES (objf)
  1055.   {
  1056.     PyObject *item = objfile_to_objfile_object (objf);

  1057.     if (!item || PyList_Append (list, item) == -1)
  1058.       {
  1059.         Py_DECREF (list);
  1060.         return NULL;
  1061.       }
  1062.   }

  1063.   return list;
  1064. }

  1065. /* Compute the list of active python type printers and store them in
  1066.    EXT_PRINTERS->py_type_printers.  The product of this function is used by
  1067.    gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
  1068.    This is the extension_language_ops.start_type_printers "method".  */

  1069. static void
  1070. gdbpy_start_type_printers (const struct extension_language_defn *extlang,
  1071.                            struct ext_lang_type_printers *ext_printers)
  1072. {
  1073.   struct cleanup *cleanups;
  1074.   PyObject *type_module, *func = NULL, *printers_obj = NULL;

  1075.   if (!gdb_python_initialized)
  1076.     return;

  1077.   cleanups = ensure_python_env (get_current_arch (), current_language);

  1078.   type_module = PyImport_ImportModule ("gdb.types");
  1079.   if (type_module == NULL)
  1080.     {
  1081.       gdbpy_print_stack ();
  1082.       goto done;
  1083.     }

  1084.   func = PyObject_GetAttrString (type_module, "get_type_recognizers");
  1085.   if (func == NULL)
  1086.     {
  1087.       gdbpy_print_stack ();
  1088.       goto done;
  1089.     }

  1090.   printers_obj = PyObject_CallFunctionObjArgs (func, (char *) NULL);
  1091.   if (printers_obj == NULL)
  1092.     gdbpy_print_stack ();
  1093.   else
  1094.     ext_printers->py_type_printers = printers_obj;

  1095. done:
  1096.   Py_XDECREF (type_module);
  1097.   Py_XDECREF (func);
  1098.   do_cleanups (cleanups);
  1099. }

  1100. /* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
  1101.    a newly allocated string holding the type's replacement name, and return
  1102.    EXT_LANG_RC_OK.  The caller is responsible for freeing the string.
  1103.    If there's a Python error return EXT_LANG_RC_ERROR.
  1104.    Otherwise, return EXT_LANG_RC_NOP.
  1105.    This is the extension_language_ops.apply_type_printers "method".  */

  1106. static enum ext_lang_rc
  1107. gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
  1108.                            const struct ext_lang_type_printers *ext_printers,
  1109.                            struct type *type, char **prettied_type)
  1110. {
  1111.   struct cleanup *cleanups;
  1112.   PyObject *type_obj, *type_module = NULL, *func = NULL;
  1113.   PyObject *result_obj = NULL;
  1114.   PyObject *printers_obj = ext_printers->py_type_printers;
  1115.   char *result = NULL;

  1116.   if (printers_obj == NULL)
  1117.     return EXT_LANG_RC_NOP;

  1118.   if (!gdb_python_initialized)
  1119.     return EXT_LANG_RC_NOP;

  1120.   cleanups = ensure_python_env (get_current_arch (), current_language);

  1121.   type_obj = type_to_type_object (type);
  1122.   if (type_obj == NULL)
  1123.     {
  1124.       gdbpy_print_stack ();
  1125.       goto done;
  1126.     }

  1127.   type_module = PyImport_ImportModule ("gdb.types");
  1128.   if (type_module == NULL)
  1129.     {
  1130.       gdbpy_print_stack ();
  1131.       goto done;
  1132.     }

  1133.   func = PyObject_GetAttrString (type_module, "apply_type_recognizers");
  1134.   if (func == NULL)
  1135.     {
  1136.       gdbpy_print_stack ();
  1137.       goto done;
  1138.     }

  1139.   result_obj = PyObject_CallFunctionObjArgs (func, printers_obj,
  1140.                                              type_obj, (char *) NULL);
  1141.   if (result_obj == NULL)
  1142.     {
  1143.       gdbpy_print_stack ();
  1144.       goto done;
  1145.     }

  1146.   if (result_obj != Py_None)
  1147.     {
  1148.       result = python_string_to_host_string (result_obj);
  1149.       if (result == NULL)
  1150.         gdbpy_print_stack ();
  1151.     }

  1152. done:
  1153.   Py_XDECREF (type_obj);
  1154.   Py_XDECREF (type_module);
  1155.   Py_XDECREF (func);
  1156.   Py_XDECREF (result_obj);
  1157.   do_cleanups (cleanups);
  1158.   if (result != NULL)
  1159.     *prettied_type = result;
  1160.   return result != NULL ? EXT_LANG_RC_OK : EXT_LANG_RC_ERROR;
  1161. }

  1162. /* Free the result of start_type_printers.
  1163.    This is the extension_language_ops.free_type_printers "method".  */

  1164. static void
  1165. gdbpy_free_type_printers (const struct extension_language_defn *extlang,
  1166.                           struct ext_lang_type_printers *ext_printers)
  1167. {
  1168.   struct cleanup *cleanups;
  1169.   PyObject *printers = ext_printers->py_type_printers;

  1170.   if (printers == NULL)
  1171.     return;

  1172.   if (!gdb_python_initialized)
  1173.     return;

  1174.   cleanups = ensure_python_env (get_current_arch (), current_language);
  1175.   Py_DECREF (printers);
  1176.   do_cleanups (cleanups);
  1177. }

  1178. #else /* HAVE_PYTHON */

  1179. /* Dummy implementation of the gdb "python-interactive" and "python"
  1180.    command. */

  1181. static void
  1182. python_interactive_command (char *arg, int from_tty)
  1183. {
  1184.   arg = skip_spaces (arg);
  1185.   if (arg && *arg)
  1186.     error (_("Python scripting is not supported in this copy of GDB."));
  1187.   else
  1188.     {
  1189.       struct command_line *l = get_command_line (python_control, "");
  1190.       struct cleanup *cleanups = make_cleanup_free_command_lines (&l);

  1191.       execute_control_command_untraced (l);
  1192.       do_cleanups (cleanups);
  1193.     }
  1194. }

  1195. static void
  1196. python_command (char *arg, int from_tty)
  1197. {
  1198.   python_interactive_command (arg, from_tty);
  1199. }

  1200. #endif /* HAVE_PYTHON */



  1201. /* Lists for 'set python' commands.  */

  1202. static struct cmd_list_element *user_set_python_list;
  1203. static struct cmd_list_element *user_show_python_list;

  1204. /* Function for use by 'set python' prefix command.  */

  1205. static void
  1206. user_set_python (char *args, int from_tty)
  1207. {
  1208.   help_list (user_set_python_list, "set python ", all_commands,
  1209.              gdb_stdout);
  1210. }

  1211. /* Function for use by 'show python' prefix command.  */

  1212. static void
  1213. user_show_python (char *args, int from_tty)
  1214. {
  1215.   cmd_show_list (user_show_python_list, from_tty, "");
  1216. }

  1217. /* Initialize the Python code.  */

  1218. #ifdef HAVE_PYTHON

  1219. /* This is installed as a final cleanup and cleans up the
  1220.    interpreter.  This lets Python's 'atexit' work.  */

  1221. static void
  1222. finalize_python (void *ignore)
  1223. {
  1224.   struct active_ext_lang_state *previous_active;

  1225.   /* We don't use ensure_python_env here because if we ever ran the
  1226.      cleanup, gdb would crash -- because the cleanup calls into the
  1227.      Python interpreter, which we are about to destroy.  It seems
  1228.      clearer to make the needed calls explicitly here than to create a
  1229.      cleanup and then mysteriously discard it.  */

  1230.   /* This is only called as a final cleanup so we can assume the active
  1231.      SIGINT handler is gdb's.  We still need to tell it to notify Python.  */
  1232.   previous_active = set_active_ext_lang (&extension_language_python);

  1233.   (void) PyGILState_Ensure ();
  1234.   python_gdbarch = target_gdbarch ();
  1235.   python_language = current_language;

  1236.   Py_Finalize ();

  1237.   restore_active_ext_lang (previous_active);
  1238. }
  1239. #endif

  1240. /* Provide a prototype to silence -Wmissing-prototypes.  */
  1241. extern initialize_file_ftype _initialize_python;

  1242. void
  1243. _initialize_python (void)
  1244. {
  1245.   char *progname;
  1246. #ifdef IS_PY3K
  1247.   int i;
  1248.   size_t progsize, count;
  1249.   char *oldloc;
  1250.   wchar_t *progname_copy;
  1251. #endif

  1252.   add_com ("python-interactive", class_obscure,
  1253.            python_interactive_command,
  1254. #ifdef HAVE_PYTHON
  1255.            _("\
  1256. Start an interactive Python prompt.\n\
  1257. \n\
  1258. To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
  1259. prompt).\n\
  1260. \n\
  1261. Alternatively, a single-line Python command can be given as an\n\
  1262. argument, and if the command is an expression, the result will be\n\
  1263. printed.  For example:\n\
  1264. \n\
  1265.     (gdb) python-interactive 2 + 3\n\
  1266.     5\n\
  1267. ")
  1268. #else /* HAVE_PYTHON */
  1269.            _("\
  1270. Start a Python interactive prompt.\n\
  1271. \n\
  1272. Python scripting is not supported in this copy of GDB.\n\
  1273. This command is only a placeholder.")
  1274. #endif /* HAVE_PYTHON */
  1275.            );
  1276.   add_com_alias ("pi", "python-interactive", class_obscure, 1);

  1277.   add_com ("python", class_obscure, python_command,
  1278. #ifdef HAVE_PYTHON
  1279.            _("\
  1280. Evaluate a Python command.\n\
  1281. \n\
  1282. The command can be given as an argument, for instance:\n\
  1283. \n\
  1284.     python print 23\n\
  1285. \n\
  1286. If no argument is given, the following lines are read and used\n\
  1287. as the Python commands.  Type a line containing \"end\" to indicate\n\
  1288. the end of the command.")
  1289. #else /* HAVE_PYTHON */
  1290.            _("\
  1291. Evaluate a Python command.\n\
  1292. \n\
  1293. Python scripting is not supported in this copy of GDB.\n\
  1294. This command is only a placeholder.")
  1295. #endif /* HAVE_PYTHON */
  1296.            );
  1297.   add_com_alias ("py", "python", class_obscure, 1);

  1298.   /* Add set/show python print-stack.  */
  1299.   add_prefix_cmd ("python", no_class, user_show_python,
  1300.                   _("Prefix command for python preference settings."),
  1301.                   &user_show_python_list, "show python ", 0,
  1302.                   &showlist);

  1303.   add_prefix_cmd ("python", no_class, user_set_python,
  1304.                   _("Prefix command for python preference settings."),
  1305.                   &user_set_python_list, "set python ", 0,
  1306.                   &setlist);

  1307.   add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
  1308.                         &gdbpy_should_print_stack, _("\
  1309. Set mode for Python stack dump on error."), _("\
  1310. Show the mode of Python stack printing on error."), _("\
  1311. none  == no stack or message will be printed.\n\
  1312. full == a message and a stack will be printed.\n\
  1313. message == an error message without a stack will be printed."),
  1314.                         NULL, NULL,
  1315.                         &user_set_python_list,
  1316.                         &user_show_python_list);

  1317. #ifdef HAVE_PYTHON
  1318. #ifdef WITH_PYTHON_PATH
  1319.   /* Work around problem where python gets confused about where it is,
  1320.      and then can't find its libraries, etc.
  1321.      NOTE: Python assumes the following layout:
  1322.      /foo/bin/python
  1323.      /foo/lib/pythonX.Y/...
  1324.      This must be done before calling Py_Initialize.  */
  1325.   progname = concat (ldirname (python_libdir), SLASH_STRING, "bin",
  1326.                      SLASH_STRING, "python", NULL);
  1327. #ifdef IS_PY3K
  1328.   oldloc = setlocale (LC_ALL, NULL);
  1329.   setlocale (LC_ALL, "");
  1330.   progsize = strlen (progname);
  1331.   if (progsize == (size_t) -1)
  1332.     {
  1333.       fprintf (stderr, "Could not convert python path to string\n");
  1334.       return;
  1335.     }
  1336.   progname_copy = PyMem_Malloc ((progsize + 1) * sizeof (wchar_t));
  1337.   if (!progname_copy)
  1338.     {
  1339.       fprintf (stderr, "out of memory\n");
  1340.       return;
  1341.     }
  1342.   count = mbstowcs (progname_copy, progname, progsize + 1);
  1343.   if (count == (size_t) -1)
  1344.     {
  1345.       fprintf (stderr, "Could not convert python path to string\n");
  1346.       return;
  1347.     }
  1348.   setlocale (LC_ALL, oldloc);

  1349.   /* Note that Py_SetProgramName expects the string it is passed to
  1350.      remain alive for the duration of the program's execution, so
  1351.      it is not freed after this call.  */
  1352.   Py_SetProgramName (progname_copy);
  1353. #else
  1354.   Py_SetProgramName (progname);
  1355. #endif
  1356. #endif

  1357.   Py_Initialize ();
  1358.   PyEval_InitThreads ();

  1359. #ifdef IS_PY3K
  1360.   gdb_module = PyModule_Create (&GdbModuleDef);
  1361.   /* Add _gdb module to the list of known built-in modules.  */
  1362.   _PyImport_FixupBuiltin (gdb_module, "_gdb");
  1363. #else
  1364.   gdb_module = Py_InitModule ("_gdb", GdbMethods);
  1365. #endif
  1366.   if (gdb_module == NULL)
  1367.     goto fail;

  1368.   /* The casts to (char*) are for python 2.4.  */
  1369.   if (PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version) < 0
  1370.       || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG",
  1371.                                      (char*) host_name) < 0
  1372.       || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
  1373.                                      (char*) target_name) < 0)
  1374.     goto fail;

  1375.   /* Add stream constants.  */
  1376.   if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
  1377.       || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
  1378.       || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
  1379.     goto fail;

  1380.   gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
  1381.   if (gdbpy_gdb_error == NULL
  1382.       || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
  1383.     goto fail;

  1384.   gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
  1385.                                                gdbpy_gdb_error, NULL);
  1386.   if (gdbpy_gdb_memory_error == NULL
  1387.       || gdb_pymodule_addobject (gdb_module, "MemoryError",
  1388.                                  gdbpy_gdb_memory_error) < 0)
  1389.     goto fail;

  1390.   gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
  1391.   if (gdbpy_gdberror_exc == NULL
  1392.       || gdb_pymodule_addobject (gdb_module, "GdbError",
  1393.                                  gdbpy_gdberror_exc) < 0)
  1394.     goto fail;

  1395.   gdbpy_initialize_gdb_readline ();

  1396.   if (gdbpy_initialize_auto_load () < 0
  1397.       || gdbpy_initialize_values () < 0
  1398.       || gdbpy_initialize_frames () < 0
  1399.       || gdbpy_initialize_commands () < 0
  1400.       || gdbpy_initialize_symbols () < 0
  1401.       || gdbpy_initialize_symtabs () < 0
  1402.       || gdbpy_initialize_blocks () < 0
  1403.       || gdbpy_initialize_functions () < 0
  1404.       || gdbpy_initialize_parameters () < 0
  1405.       || gdbpy_initialize_types () < 0
  1406.       || gdbpy_initialize_pspace () < 0
  1407.       || gdbpy_initialize_objfile () < 0
  1408.       || gdbpy_initialize_breakpoints () < 0
  1409.       || gdbpy_initialize_finishbreakpoints () < 0
  1410.       || gdbpy_initialize_lazy_string () < 0
  1411.       || gdbpy_initialize_linetable () < 0
  1412.       || gdbpy_initialize_thread () < 0
  1413.       || gdbpy_initialize_inferior () < 0
  1414.       || gdbpy_initialize_events () < 0
  1415.       || gdbpy_initialize_eventregistry () < 0
  1416.       || gdbpy_initialize_py_events () < 0
  1417.       || gdbpy_initialize_event () < 0
  1418.       || gdbpy_initialize_stop_event () < 0
  1419.       || gdbpy_initialize_signal_event () < 0
  1420.       || gdbpy_initialize_breakpoint_event () < 0
  1421.       || gdbpy_initialize_continue_event () < 0
  1422.       || gdbpy_initialize_inferior_call_pre_event () < 0
  1423.       || gdbpy_initialize_inferior_call_post_event () < 0
  1424.       || gdbpy_initialize_register_changed_event () < 0
  1425.       || gdbpy_initialize_memory_changed_event () < 0
  1426.       || gdbpy_initialize_exited_event () < 0
  1427.       || gdbpy_initialize_thread_event () < 0
  1428.       || gdbpy_initialize_new_objfile_event ()  < 0
  1429.       || gdbpy_initialize_clear_objfiles_event ()  < 0
  1430.       || gdbpy_initialize_arch () < 0
  1431.       || gdbpy_initialize_xmethods () < 0)
  1432.     goto fail;

  1433.   gdbpy_to_string_cst = PyString_FromString ("to_string");
  1434.   if (gdbpy_to_string_cst == NULL)
  1435.     goto fail;
  1436.   gdbpy_children_cst = PyString_FromString ("children");
  1437.   if (gdbpy_children_cst == NULL)
  1438.     goto fail;
  1439.   gdbpy_display_hint_cst = PyString_FromString ("display_hint");
  1440.   if (gdbpy_display_hint_cst == NULL)
  1441.     goto fail;
  1442.   gdbpy_doc_cst = PyString_FromString ("__doc__");
  1443.   if (gdbpy_doc_cst == NULL)
  1444.     goto fail;
  1445.   gdbpy_enabled_cst = PyString_FromString ("enabled");
  1446.   if (gdbpy_enabled_cst == NULL)
  1447.     goto fail;
  1448.   gdbpy_value_cst = PyString_FromString ("value");
  1449.   if (gdbpy_value_cst == NULL)
  1450.     goto fail;

  1451.   /* Release the GIL while gdb runs.  */
  1452.   PyThreadState_Swap (NULL);
  1453.   PyEval_ReleaseLock ();

  1454.   make_final_cleanup (finalize_python, NULL);

  1455.   gdb_python_initialized = 1;
  1456.   return;

  1457. fail:
  1458.   gdbpy_print_stack ();
  1459.   /* Do not set 'gdb_python_initialized'.  */
  1460.   return;

  1461. #endif /* HAVE_PYTHON */
  1462. }

  1463. #ifdef HAVE_PYTHON

  1464. /* Perform the remaining python initializations.
  1465.    These must be done after GDB is at least mostly initialized.
  1466.    E.g., The "info pretty-printer" command needs the "info" prefix
  1467.    command installed.
  1468.    This is the extension_language_ops.finish_initialization "method".  */

  1469. static void
  1470. gdbpy_finish_initialization (const struct extension_language_defn *extlang)
  1471. {
  1472.   PyObject *m;
  1473.   char *gdb_pythondir;
  1474.   PyObject *sys_path;
  1475.   struct cleanup *cleanup;

  1476.   cleanup = ensure_python_env (get_current_arch (), current_language);

  1477.   /* Add the initial data-directory to sys.path.  */

  1478.   gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
  1479.   make_cleanup (xfree, gdb_pythondir);

  1480.   sys_path = PySys_GetObject ("path");

  1481.   /* If sys.path is not defined yet, define it first.  */
  1482.   if (!(sys_path && PyList_Check (sys_path)))
  1483.     {
  1484. #ifdef IS_PY3K
  1485.       PySys_SetPath (L"");
  1486. #else
  1487.       PySys_SetPath ("");
  1488. #endif
  1489.       sys_path = PySys_GetObject ("path");
  1490.     }
  1491.   if (sys_path && PyList_Check (sys_path))
  1492.     {
  1493.       PyObject *pythondir;
  1494.       int err;

  1495.       pythondir = PyString_FromString (gdb_pythondir);
  1496.       if (pythondir == NULL)
  1497.         goto fail;

  1498.       err = PyList_Insert (sys_path, 0, pythondir);
  1499.       Py_DECREF (pythondir);
  1500.       if (err)
  1501.         goto fail;
  1502.     }
  1503.   else
  1504.     goto fail;

  1505.   /* Import the gdb module to finish the initialization, and
  1506.      add it to __main__ for convenience.  */
  1507.   m = PyImport_AddModule ("__main__");
  1508.   if (m == NULL)
  1509.     goto fail;

  1510.   gdb_python_module = PyImport_ImportModule ("gdb");
  1511.   if (gdb_python_module == NULL)
  1512.     {
  1513.       gdbpy_print_stack ();
  1514.       /* This is passed in one call to warning so that blank lines aren't
  1515.          inserted between each line of text.  */
  1516.       warning (_("\n"
  1517.                  "Could not load the Python gdb module from `%s'.\n"
  1518.                  "Limited Python support is available from the _gdb module.\n"
  1519.                  "Suggest passing --data-directory=/path/to/gdb/data-directory.\n"),
  1520.                  gdb_pythondir);
  1521.       do_cleanups (cleanup);
  1522.       return;
  1523.     }

  1524.   if (gdb_pymodule_addobject (m, "gdb", gdb_python_module) < 0)
  1525.     goto fail;

  1526.   /* Keep the reference to gdb_python_module since it is in a global
  1527.      variable.  */

  1528.   do_cleanups (cleanup);
  1529.   return;

  1530. fail:
  1531.   gdbpy_print_stack ();
  1532.   warning (_("internal error: Unhandled Python exception"));
  1533.   do_cleanups (cleanup);
  1534. }

  1535. /* Return non-zero if Python has successfully initialized.
  1536.    This is the extension_languages_ops.initialized "method".  */

  1537. static int
  1538. gdbpy_initialized (const struct extension_language_defn *extlang)
  1539. {
  1540.   return gdb_python_initialized;
  1541. }

  1542. #endif /* HAVE_PYTHON */



  1543. #ifdef HAVE_PYTHON

  1544. static PyMethodDef GdbMethods[] =
  1545. {
  1546.   { "history", gdbpy_history, METH_VARARGS,
  1547.     "Get a value from history" },
  1548.   { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
  1549.     "execute (command [, from_tty] [, to_string]) -> [String]\n\
  1550. Evaluate command, a string, as a gdb CLI command.  Optionally returns\n\
  1551. a Python String containing the output of the command if to_string is\n\
  1552. set to True." },
  1553.   { "parameter", gdbpy_parameter, METH_VARARGS,
  1554.     "Return a gdb parameter's value" },

  1555.   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
  1556.     "Return a tuple of all breakpoint objects" },

  1557.   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
  1558.     "Find the default visualizer for a Value." },

  1559.   { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
  1560.     "Return the current Progspace." },
  1561.   { "progspaces", gdbpy_progspaces, METH_NOARGS,
  1562.     "Return a sequence of all progspaces." },

  1563.   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
  1564.     "Return the current Objfile being loaded, or None." },
  1565.   { "objfiles", gdbpy_objfiles, METH_NOARGS,
  1566.     "Return a sequence of all loaded objfiles." },

  1567.   { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
  1568.     "newest_frame () -> gdb.Frame.\n\
  1569. Return the newest frame object." },
  1570.   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
  1571.     "selected_frame () -> gdb.Frame.\n\
  1572. Return the selected frame object." },
  1573.   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
  1574.     "stop_reason_string (Integer) -> String.\n\
  1575. Return a string explaining unwind stop reason." },

  1576.   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
  1577.     METH_VARARGS | METH_KEYWORDS,
  1578.     "lookup_type (name [, block]) -> type\n\
  1579. Return a Type corresponding to the given name." },
  1580.   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
  1581.     METH_VARARGS | METH_KEYWORDS,
  1582.     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
  1583. Return a tuple with the symbol corresponding to the given name (or None) and\n\
  1584. a boolean indicating if name is a field of the current implied argument\n\
  1585. `this' (when the current language is object-oriented)." },
  1586.   { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
  1587.     METH_VARARGS | METH_KEYWORDS,
  1588.     "lookup_global_symbol (name [, domain]) -> symbol\n\
  1589. Return the symbol corresponding to the given name (or None)." },

  1590.   { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
  1591.     METH_VARARGS | METH_KEYWORDS,
  1592.     "lookup_objfile (name, [by_build_id]) -> objfile\n\
  1593. Look up the specified objfile.\n\
  1594. If by_build_id is True, the objfile is looked up by using name\n\
  1595. as its build id." },

  1596.   { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
  1597.     "Return the block containing the given pc value, or None." },
  1598.   { "solib_name", gdbpy_solib_name, METH_VARARGS,
  1599.     "solib_name (Long) -> String.\n\
  1600. Return the name of the shared library holding a given address, or None." },
  1601.   { "decode_line", gdbpy_decode_line, METH_VARARGS,
  1602.     "decode_line (String) -> Tuple.  Decode a string argument the way\n\
  1603. that 'break' or 'edit' does.  Return a tuple containing two elements.\n\
  1604. The first element contains any unparsed portion of the String parameter\n\
  1605. (or None if the string was fully parsed).  The second element contains\n\
  1606. a tuple that contains all the locations that match, represented as\n\
  1607. gdb.Symtab_and_line objects (or None)."},
  1608.   { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
  1609.     "parse_and_eval (String) -> Value.\n\
  1610. Parse String as an expression, evaluate it, and return the result as a Value."
  1611.   },
  1612.   { "find_pc_line", gdbpy_find_pc_line, METH_VARARGS,
  1613.     "find_pc_line (pc) -> Symtab_and_line.\n\
  1614. Return the gdb.Symtab_and_line object corresponding to the pc value." },

  1615.   { "post_event", gdbpy_post_event, METH_VARARGS,
  1616.     "Post an event into gdb's event loop." },

  1617.   { "target_charset", gdbpy_target_charset, METH_NOARGS,
  1618.     "target_charset () -> string.\n\
  1619. Return the name of the current target charset." },
  1620.   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
  1621.     "target_wide_charset () -> string.\n\
  1622. Return the name of the current target wide charset." },

  1623.   { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
  1624.     "string_to_argv (String) -> Array.\n\
  1625. Parse String and return an argv-like array.\n\
  1626. Arguments are separate by spaces and may be quoted."
  1627.   },
  1628.   { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
  1629.     "Write a string using gdb's filtered stream." },
  1630.   { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
  1631.     "Flush gdb's filtered stdout stream." },
  1632.   { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
  1633.     "selected_thread () -> gdb.InferiorThread.\n\
  1634. Return the selected thread object." },
  1635.   { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
  1636.     "selected_inferior () -> gdb.Inferior.\n\
  1637. Return the selected inferior object." },
  1638.   { "inferiors", gdbpy_inferiors, METH_NOARGS,
  1639.     "inferiors () -> (gdb.Inferior, ...).\n\
  1640. Return a tuple containing all inferiors." },
  1641.   {NULL, NULL, 0, NULL}
  1642. };

  1643. #ifdef IS_PY3K
  1644. static struct PyModuleDef GdbModuleDef =
  1645. {
  1646.   PyModuleDef_HEAD_INIT,
  1647.   "_gdb",
  1648.   NULL,
  1649.   -1,
  1650.   GdbMethods,
  1651.   NULL,
  1652.   NULL,
  1653.   NULL,
  1654.   NULL
  1655. };
  1656. #endif
  1657. #endif /* HAVE_PYTHON */