GDB (API)
/home/stan/gdb/src/gdb/python/python.c
Go to the documentation of this file.
00001 /* General python/gdb code
00002 
00003    Copyright (C) 2008-2013 Free Software Foundation, Inc.
00004 
00005    This file is part of GDB.
00006 
00007    This program is free software; you can redistribute it and/or modify
00008    it under the terms of the GNU General Public License as published by
00009    the Free Software Foundation; either version 3 of the License, or
00010    (at your option) any later version.
00011 
00012    This program is distributed in the hope that it will be useful,
00013    but WITHOUT ANY WARRANTY; without even the implied warranty of
00014    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015    GNU General Public License for more details.
00016 
00017    You should have received a copy of the GNU General Public License
00018    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00019 
00020 #include "defs.h"
00021 #include "arch-utils.h"
00022 #include "command.h"
00023 #include "ui-out.h"
00024 #include "cli/cli-script.h"
00025 #include "gdbcmd.h"
00026 #include "progspace.h"
00027 #include "objfiles.h"
00028 #include "value.h"
00029 #include "language.h"
00030 #include "exceptions.h"
00031 #include "event-loop.h"
00032 #include "serial.h"
00033 #include "readline/tilde.h"
00034 #include "python.h"
00035 #include "cli/cli-utils.h"
00036 
00037 #include <ctype.h>
00038 
00039 /* Declared constants and enum for python stack printing.  */
00040 static const char python_excp_none[] = "none";
00041 static const char python_excp_full[] = "full";
00042 static const char python_excp_message[] = "message";
00043 
00044 /* "set python print-stack" choices.  */
00045 static const char *const python_excp_enums[] =
00046   {
00047     python_excp_none,
00048     python_excp_full,
00049     python_excp_message,
00050     NULL
00051   };
00052 
00053 /* The exception printing variable.  'full' if we want to print the
00054    error message and stack, 'none' if we want to print nothing, and
00055    'message' if we only want to print the error message.  'message' is
00056    the default.  */
00057 static const char *gdbpy_should_print_stack = python_excp_message;
00058 
00059 #ifdef HAVE_PYTHON
00060 
00061 #include "libiberty.h"
00062 #include "cli/cli-decode.h"
00063 #include "charset.h"
00064 #include "top.h"
00065 #include "solib.h"
00066 #include "python-internal.h"
00067 #include "linespec.h"
00068 #include "source.h"
00069 #include "version.h"
00070 #include "target.h"
00071 #include "gdbthread.h"
00072 #include "observer.h"
00073 #include "interps.h"
00074 #include "event-top.h"
00075 
00076 /* True if Python has been successfully initialized, false
00077    otherwise.  */
00078 
00079 int gdb_python_initialized;
00080 
00081 static PyMethodDef GdbMethods[];
00082 
00083 #ifdef IS_PY3K
00084 static struct PyModuleDef GdbModuleDef;
00085 #endif
00086 
00087 PyObject *gdb_module;
00088 PyObject *gdb_python_module;
00089 
00090 /* Some string constants we may wish to use.  */
00091 PyObject *gdbpy_to_string_cst;
00092 PyObject *gdbpy_children_cst;
00093 PyObject *gdbpy_display_hint_cst;
00094 PyObject *gdbpy_doc_cst;
00095 PyObject *gdbpy_enabled_cst;
00096 PyObject *gdbpy_value_cst;
00097 
00098 /* The GdbError exception.  */
00099 PyObject *gdbpy_gdberror_exc;
00100 
00101 /* The `gdb.error' base class.  */
00102 PyObject *gdbpy_gdb_error;
00103 
00104 /* The `gdb.MemoryError' exception.  */
00105 PyObject *gdbpy_gdb_memory_error;
00106 
00107 /* Architecture and language to be used in callbacks from
00108    the Python interpreter.  */
00109 struct gdbarch *python_gdbarch;
00110 const struct language_defn *python_language;
00111 
00112 /* Restore global language and architecture and Python GIL state
00113    when leaving the Python interpreter.  */
00114 
00115 struct python_env
00116 {
00117   PyGILState_STATE state;
00118   struct gdbarch *gdbarch;
00119   const struct language_defn *language;
00120   PyObject *error_type, *error_value, *error_traceback;
00121 };
00122 
00123 static void
00124 restore_python_env (void *p)
00125 {
00126   struct python_env *env = (struct python_env *)p;
00127 
00128   /* Leftover Python error is forbidden by Python Exception Handling.  */
00129   if (PyErr_Occurred ())
00130     {
00131       /* This order is similar to the one calling error afterwards. */
00132       gdbpy_print_stack ();
00133       warning (_("internal error: Unhandled Python exception"));
00134     }
00135 
00136   PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
00137 
00138   PyGILState_Release (env->state);
00139   python_gdbarch = env->gdbarch;
00140   python_language = env->language;
00141   xfree (env);
00142 }
00143 
00144 /* Called before entering the Python interpreter to install the
00145    current language and architecture to be used for Python values.  */
00146 
00147 struct cleanup *
00148 ensure_python_env (struct gdbarch *gdbarch,
00149                    const struct language_defn *language)
00150 {
00151   struct python_env *env = xmalloc (sizeof *env);
00152 
00153   /* We should not ever enter Python unless initialized.  */
00154   if (!gdb_python_initialized)
00155     error (_("Python not initialized"));
00156 
00157   env->state = PyGILState_Ensure ();
00158   env->gdbarch = python_gdbarch;
00159   env->language = python_language;
00160 
00161   python_gdbarch = gdbarch;
00162   python_language = language;
00163 
00164   /* Save it and ensure ! PyErr_Occurred () afterwards.  */
00165   PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
00166   
00167   return make_cleanup (restore_python_env, env);
00168 }
00169 
00170 /* Clear the quit flag.  */
00171 
00172 void
00173 clear_quit_flag (void)
00174 {
00175   /* This clears the flag as a side effect.  */
00176   PyOS_InterruptOccurred ();
00177 }
00178 
00179 /* Set the quit flag.  */
00180 
00181 void
00182 set_quit_flag (void)
00183 {
00184   PyErr_SetInterrupt ();
00185 }
00186 
00187 /* Return true if the quit flag has been set, false otherwise.  */
00188 
00189 int
00190 check_quit_flag (void)
00191 {
00192   return PyOS_InterruptOccurred ();
00193 }
00194 
00195 /* Evaluate a Python command like PyRun_SimpleString, but uses
00196    Py_single_input which prints the result of expressions, and does
00197    not automatically print the stack on errors.  */
00198 
00199 static int
00200 eval_python_command (const char *command)
00201 {
00202   PyObject *m, *d, *v;
00203 
00204   m = PyImport_AddModule ("__main__");
00205   if (m == NULL)
00206     return -1;
00207 
00208   d = PyModule_GetDict (m);
00209   if (d == NULL)
00210     return -1;
00211   v = PyRun_StringFlags (command, Py_single_input, d, d, NULL);
00212   if (v == NULL)
00213     return -1;
00214 
00215   Py_DECREF (v);
00216 #ifndef IS_PY3K
00217   if (Py_FlushLine ())
00218     PyErr_Clear ();
00219 #endif
00220 
00221   return 0;
00222 }
00223 
00224 /* Implementation of the gdb "python-interactive" command.  */
00225 
00226 static void
00227 python_interactive_command (char *arg, int from_tty)
00228 {
00229   struct cleanup *cleanup;
00230   int err;
00231 
00232   cleanup = make_cleanup_restore_integer (&interpreter_async);
00233   interpreter_async = 0;
00234 
00235   arg = skip_spaces (arg);
00236 
00237   ensure_python_env (get_current_arch (), current_language);
00238 
00239   if (arg && *arg)
00240     {
00241       int len = strlen (arg);
00242       char *script = xmalloc (len + 2);
00243 
00244       strcpy (script, arg);
00245       script[len] = '\n';
00246       script[len + 1] = '\0';
00247       err = eval_python_command (script);
00248       xfree (script);
00249     }
00250   else
00251     {
00252       err = PyRun_InteractiveLoop (instream, "<stdin>");
00253       dont_repeat ();
00254     }
00255 
00256   if (err)
00257     {
00258       gdbpy_print_stack ();
00259       error (_("Error while executing Python code."));
00260     }
00261 
00262   do_cleanups (cleanup);
00263 }
00264 
00265 /* A wrapper around PyRun_SimpleFile.  FILE is the Python script to run
00266    named FILENAME.
00267 
00268    On Windows hosts few users would build Python themselves (this is no
00269    trivial task on this platform), and thus use binaries built by
00270    someone else instead.  There may happen situation where the Python
00271    library and GDB are using two different versions of the C runtime
00272    library.  Python, being built with VC, would use one version of the
00273    msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
00274    A FILE * from one runtime does not necessarily operate correctly in
00275    the other runtime.
00276 
00277    To work around this potential issue, we create on Windows hosts the
00278    FILE object using Python routines, thus making sure that it is
00279    compatible with the Python library.  */
00280 
00281 static void
00282 python_run_simple_file (FILE *file, const char *filename)
00283 {
00284 #ifndef _WIN32
00285 
00286   PyRun_SimpleFile (file, filename);
00287 
00288 #else /* _WIN32 */
00289 
00290   char *full_path;
00291   PyObject *python_file;
00292   struct cleanup *cleanup;
00293 
00294   /* Because we have a string for a filename, and are using Python to
00295      open the file, we need to expand any tilde in the path first.  */
00296   full_path = tilde_expand (filename);
00297   cleanup = make_cleanup (xfree, full_path);
00298   python_file = PyFile_FromString (full_path, "r");
00299   if (! python_file)
00300     {
00301       do_cleanups (cleanup);
00302       gdbpy_print_stack ();
00303       error (_("Error while opening file: %s"), full_path);
00304     }
00305  
00306   make_cleanup_py_decref (python_file);
00307   PyRun_SimpleFile (PyFile_AsFile (python_file), filename);
00308   do_cleanups (cleanup);
00309 
00310 #endif /* _WIN32 */
00311 }
00312 
00313 /* Given a command_line, return a command string suitable for passing
00314    to Python.  Lines in the string are separated by newlines.  The
00315    return value is allocated using xmalloc and the caller is
00316    responsible for freeing it.  */
00317 
00318 static char *
00319 compute_python_string (struct command_line *l)
00320 {
00321   struct command_line *iter;
00322   char *script = NULL;
00323   int size = 0;
00324   int here;
00325 
00326   for (iter = l; iter; iter = iter->next)
00327     size += strlen (iter->line) + 1;
00328 
00329   script = xmalloc (size + 1);
00330   here = 0;
00331   for (iter = l; iter; iter = iter->next)
00332     {
00333       int len = strlen (iter->line);
00334 
00335       strcpy (&script[here], iter->line);
00336       here += len;
00337       script[here++] = '\n';
00338     }
00339   script[here] = '\0';
00340   return script;
00341 }
00342 
00343 /* Take a command line structure representing a 'python' command, and
00344    evaluate its body using the Python interpreter.  */
00345 
00346 void
00347 eval_python_from_control_command (struct command_line *cmd)
00348 {
00349   int ret;
00350   char *script;
00351   struct cleanup *cleanup;
00352 
00353   if (cmd->body_count != 1)
00354     error (_("Invalid \"python\" block structure."));
00355 
00356   cleanup = ensure_python_env (get_current_arch (), current_language);
00357 
00358   script = compute_python_string (cmd->body_list[0]);
00359   ret = PyRun_SimpleString (script);
00360   xfree (script);
00361   if (ret)
00362     error (_("Error while executing Python code."));
00363 
00364   do_cleanups (cleanup);
00365 }
00366 
00367 /* Implementation of the gdb "python" command.  */
00368 
00369 static void
00370 python_command (char *arg, int from_tty)
00371 {
00372   struct cleanup *cleanup;
00373 
00374   cleanup = ensure_python_env (get_current_arch (), current_language);
00375 
00376   make_cleanup_restore_integer (&interpreter_async);
00377   interpreter_async = 0;
00378 
00379   arg = skip_spaces (arg);
00380   if (arg && *arg)
00381     {
00382       if (PyRun_SimpleString (arg))
00383         error (_("Error while executing Python code."));
00384     }
00385   else
00386     {
00387       struct command_line *l = get_command_line (python_control, "");
00388 
00389       make_cleanup_free_command_lines (&l);
00390       execute_control_command_untraced (l);
00391     }
00392 
00393   do_cleanups (cleanup);
00394 }
00395 
00396 
00397 
00398 /* Transform a gdb parameters's value into a Python value.  May return
00399    NULL (and set a Python exception) on error.  Helper function for
00400    get_parameter.  */
00401 PyObject *
00402 gdbpy_parameter_value (enum var_types type, void *var)
00403 {
00404   switch (type)
00405     {
00406     case var_string:
00407     case var_string_noescape:
00408     case var_optional_filename:
00409     case var_filename:
00410     case var_enum:
00411       {
00412         char *str = * (char **) var;
00413 
00414         if (! str)
00415           str = "";
00416         return PyString_Decode (str, strlen (str), host_charset (), NULL);
00417       }
00418 
00419     case var_boolean:
00420       {
00421         if (* (int *) var)
00422           Py_RETURN_TRUE;
00423         else
00424           Py_RETURN_FALSE;
00425       }
00426 
00427     case var_auto_boolean:
00428       {
00429         enum auto_boolean ab = * (enum auto_boolean *) var;
00430 
00431         if (ab == AUTO_BOOLEAN_TRUE)
00432           Py_RETURN_TRUE;
00433         else if (ab == AUTO_BOOLEAN_FALSE)
00434           Py_RETURN_FALSE;
00435         else
00436           Py_RETURN_NONE;
00437       }
00438 
00439     case var_integer:
00440       if ((* (int *) var) == INT_MAX)
00441         Py_RETURN_NONE;
00442       /* Fall through.  */
00443     case var_zinteger:
00444       return PyLong_FromLong (* (int *) var);
00445 
00446     case var_uinteger:
00447       {
00448         unsigned int val = * (unsigned int *) var;
00449 
00450         if (val == UINT_MAX)
00451           Py_RETURN_NONE;
00452         return PyLong_FromUnsignedLong (val);
00453       }
00454     }
00455 
00456   return PyErr_Format (PyExc_RuntimeError, 
00457                        _("Programmer error: unhandled type."));
00458 }
00459 
00460 /* A Python function which returns a gdb parameter's value as a Python
00461    value.  */
00462 
00463 PyObject *
00464 gdbpy_parameter (PyObject *self, PyObject *args)
00465 {
00466   struct cmd_list_element *alias, *prefix, *cmd;
00467   const char *arg;
00468   char *newarg;
00469   int found = -1;
00470   volatile struct gdb_exception except;
00471 
00472   if (! PyArg_ParseTuple (args, "s", &arg))
00473     return NULL;
00474 
00475   newarg = concat ("show ", arg, (char *) NULL);
00476 
00477   TRY_CATCH (except, RETURN_MASK_ALL)
00478     {
00479       found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
00480     }
00481   xfree (newarg);
00482   GDB_PY_HANDLE_EXCEPTION (except);
00483   if (!found)
00484     return PyErr_Format (PyExc_RuntimeError,
00485                          _("Could not find parameter `%s'."), arg);
00486 
00487   if (! cmd->var)
00488     return PyErr_Format (PyExc_RuntimeError, 
00489                          _("`%s' is not a parameter."), arg);
00490   return gdbpy_parameter_value (cmd->var_type, cmd->var);
00491 }
00492 
00493 /* Wrapper for target_charset.  */
00494 
00495 static PyObject *
00496 gdbpy_target_charset (PyObject *self, PyObject *args)
00497 {
00498   const char *cset = target_charset (python_gdbarch);
00499 
00500   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
00501 }
00502 
00503 /* Wrapper for target_wide_charset.  */
00504 
00505 static PyObject *
00506 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
00507 {
00508   const char *cset = target_wide_charset (python_gdbarch);
00509 
00510   return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
00511 }
00512 
00513 /* A Python function which evaluates a string using the gdb CLI.  */
00514 
00515 static PyObject *
00516 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
00517 {
00518   const char *arg;
00519   PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
00520   int from_tty, to_string;
00521   volatile struct gdb_exception except;
00522   static char *keywords[] = {"command", "from_tty", "to_string", NULL };
00523   char *result = NULL;
00524 
00525   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
00526                                      &PyBool_Type, &from_tty_obj,
00527                                      &PyBool_Type, &to_string_obj))
00528     return NULL;
00529 
00530   from_tty = 0;
00531   if (from_tty_obj)
00532     {
00533       int cmp = PyObject_IsTrue (from_tty_obj);
00534       if (cmp < 0)
00535         return NULL;
00536       from_tty = cmp;
00537     }
00538 
00539   to_string = 0;
00540   if (to_string_obj)
00541     {
00542       int cmp = PyObject_IsTrue (to_string_obj);
00543       if (cmp < 0)
00544         return NULL;
00545       to_string = cmp;
00546     }
00547 
00548   TRY_CATCH (except, RETURN_MASK_ALL)
00549     {
00550       /* Copy the argument text in case the command modifies it.  */
00551       char *copy = xstrdup (arg);
00552       struct cleanup *cleanup = make_cleanup (xfree, copy);
00553 
00554       make_cleanup_restore_integer (&interpreter_async);
00555       interpreter_async = 0;
00556 
00557       prevent_dont_repeat ();
00558       if (to_string)
00559         result = execute_command_to_string (copy, from_tty);
00560       else
00561         {
00562           result = NULL;
00563           execute_command (copy, from_tty);
00564         }
00565 
00566       do_cleanups (cleanup);
00567     }
00568   GDB_PY_HANDLE_EXCEPTION (except);
00569 
00570   /* Do any commands attached to breakpoint we stopped at.  */
00571   bpstat_do_actions ();
00572 
00573   if (result)
00574     {
00575       PyObject *r = PyString_FromString (result);
00576       xfree (result);
00577       return r;
00578     }
00579   Py_RETURN_NONE;
00580 }
00581 
00582 /* Implementation of gdb.solib_name (Long) -> String.
00583    Returns the name of the shared library holding a given address, or None.  */
00584 
00585 static PyObject *
00586 gdbpy_solib_name (PyObject *self, PyObject *args)
00587 {
00588   char *soname;
00589   PyObject *str_obj;
00590   gdb_py_longest pc;
00591 
00592   if (!PyArg_ParseTuple (args, GDB_PY_LL_ARG, &pc))
00593     return NULL;
00594 
00595   soname = solib_name_from_address (current_program_space, pc);
00596   if (soname)
00597     str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
00598   else
00599     {
00600       str_obj = Py_None;
00601       Py_INCREF (Py_None);
00602     }
00603 
00604   return str_obj;
00605 }
00606 
00607 /* A Python function which is a wrapper for decode_line_1.  */
00608 
00609 static PyObject *
00610 gdbpy_decode_line (PyObject *self, PyObject *args)
00611 {
00612   struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to
00613                                                   appease gcc.  */
00614   struct symtab_and_line sal;
00615   const char *arg = NULL;
00616   char *copy_to_free = NULL, *copy = NULL;
00617   struct cleanup *cleanups;
00618   PyObject *result = NULL;
00619   PyObject *return_result = NULL;
00620   PyObject *unparsed = NULL;
00621   volatile struct gdb_exception except;
00622 
00623   if (! PyArg_ParseTuple (args, "|s", &arg))
00624     return NULL;
00625 
00626   cleanups = make_cleanup (null_cleanup, NULL);
00627 
00628   sals.sals = NULL;
00629   TRY_CATCH (except, RETURN_MASK_ALL)
00630     {
00631       if (arg)
00632         {
00633           copy = xstrdup (arg);
00634           copy_to_free = copy;
00635           sals = decode_line_1 (&copy, 0, 0, 0);
00636         }
00637       else
00638         {
00639           set_default_source_symtab_and_line ();
00640           sal = get_current_source_symtab_and_line ();
00641           sals.sals = &sal;
00642           sals.nelts = 1;
00643         }
00644     }
00645 
00646   if (sals.sals != NULL && sals.sals != &sal)
00647     {
00648       make_cleanup (xfree, copy_to_free);
00649       make_cleanup (xfree, sals.sals);
00650     }
00651 
00652   if (except.reason < 0)
00653     {
00654       do_cleanups (cleanups);
00655       /* We know this will always throw.  */
00656       gdbpy_convert_exception (except);
00657       return NULL;
00658     }
00659 
00660   if (sals.nelts)
00661     {
00662       int i;
00663 
00664       result = PyTuple_New (sals.nelts);
00665       if (! result)
00666         goto error;
00667       for (i = 0; i < sals.nelts; ++i)
00668         {
00669           PyObject *obj;
00670 
00671           obj = symtab_and_line_to_sal_object (sals.sals[i]);
00672           if (! obj)
00673             {
00674               Py_DECREF (result);
00675               goto error;
00676             }
00677 
00678           PyTuple_SetItem (result, i, obj);
00679         }
00680     }
00681   else
00682     {
00683       result = Py_None;
00684       Py_INCREF (Py_None);
00685     }
00686 
00687   return_result = PyTuple_New (2);
00688   if (! return_result)
00689     {
00690       Py_DECREF (result);
00691       goto error;
00692     }
00693 
00694   if (copy && strlen (copy) > 0)
00695     {
00696       unparsed = PyString_FromString (copy);
00697       if (unparsed == NULL)
00698         {
00699           Py_DECREF (result);
00700           Py_DECREF (return_result);
00701           return_result = NULL;
00702           goto error;
00703         }
00704     }
00705   else
00706     {
00707       unparsed = Py_None;
00708       Py_INCREF (Py_None);
00709     }
00710 
00711   PyTuple_SetItem (return_result, 0, unparsed);
00712   PyTuple_SetItem (return_result, 1, result);
00713 
00714  error:
00715   do_cleanups (cleanups);
00716 
00717   return return_result;
00718 }
00719 
00720 /* Parse a string and evaluate it as an expression.  */
00721 static PyObject *
00722 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
00723 {
00724   const char *expr_str;
00725   struct value *result = NULL;
00726   volatile struct gdb_exception except;
00727 
00728   if (!PyArg_ParseTuple (args, "s", &expr_str))
00729     return NULL;
00730 
00731   TRY_CATCH (except, RETURN_MASK_ALL)
00732     {
00733       result = parse_and_eval (expr_str);
00734     }
00735   GDB_PY_HANDLE_EXCEPTION (except);
00736 
00737   return value_to_value_object (result);
00738 }
00739 
00740 /* Implementation of gdb.find_pc_line function.
00741    Returns the gdb.Symtab_and_line object corresponding to a PC value.  */
00742 
00743 static PyObject *
00744 gdbpy_find_pc_line (PyObject *self, PyObject *args)
00745 {
00746   gdb_py_ulongest pc_llu;
00747   volatile struct gdb_exception except;
00748   PyObject *result = NULL; /* init for gcc -Wall */
00749 
00750   if (!PyArg_ParseTuple (args, GDB_PY_LLU_ARG, &pc_llu))
00751     return NULL;
00752 
00753   TRY_CATCH (except, RETURN_MASK_ALL)
00754     {
00755       struct symtab_and_line sal;
00756       CORE_ADDR pc;
00757 
00758       pc = (CORE_ADDR) pc_llu;
00759       sal = find_pc_line (pc, 0);
00760       result = symtab_and_line_to_sal_object (sal);
00761     }
00762   GDB_PY_HANDLE_EXCEPTION (except);
00763 
00764   return result;
00765 }
00766 
00767 /* Read a file as Python code.
00768    FILE is the file to run.  FILENAME is name of the file FILE.
00769    This does not throw any errors.  If an exception occurs python will print
00770    the traceback and clear the error indicator.  */
00771 
00772 void
00773 source_python_script (FILE *file, const char *filename)
00774 {
00775   struct cleanup *cleanup;
00776 
00777   cleanup = ensure_python_env (get_current_arch (), current_language);
00778   python_run_simple_file (file, filename);
00779   do_cleanups (cleanup);
00780 }
00781 
00782 
00783 
00784 /* Posting and handling events.  */
00785 
00786 /* A single event.  */
00787 struct gdbpy_event
00788 {
00789   /* The Python event.  This is just a callable object.  */
00790   PyObject *event;
00791   /* The next event.  */
00792   struct gdbpy_event *next;
00793 };
00794 
00795 /* All pending events.  */
00796 static struct gdbpy_event *gdbpy_event_list;
00797 /* The final link of the event list.  */
00798 static struct gdbpy_event **gdbpy_event_list_end;
00799 
00800 /* We use a file handler, and not an async handler, so that we can
00801    wake up the main thread even when it is blocked in poll().  */
00802 static struct serial *gdbpy_event_fds[2];
00803 
00804 /* The file handler callback.  This reads from the internal pipe, and
00805    then processes the Python event queue.  This will always be run in
00806    the main gdb thread.  */
00807 
00808 static void
00809 gdbpy_run_events (struct serial *scb, void *context)
00810 {
00811   struct cleanup *cleanup;
00812 
00813   cleanup = ensure_python_env (get_current_arch (), current_language);
00814 
00815   /* Flush the fd.  Do this before flushing the events list, so that
00816      any new event post afterwards is sure to re-awake the event
00817      loop.  */
00818   while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
00819     ;
00820 
00821   while (gdbpy_event_list)
00822     {
00823       PyObject *call_result;
00824 
00825       /* Dispatching the event might push a new element onto the event
00826          loop, so we update here "atomically enough".  */
00827       struct gdbpy_event *item = gdbpy_event_list;
00828       gdbpy_event_list = gdbpy_event_list->next;
00829       if (gdbpy_event_list == NULL)
00830         gdbpy_event_list_end = &gdbpy_event_list;
00831 
00832       /* Ignore errors.  */
00833       call_result = PyObject_CallObject (item->event, NULL);
00834       if (call_result == NULL)
00835         PyErr_Clear ();
00836 
00837       Py_XDECREF (call_result);
00838       Py_DECREF (item->event);
00839       xfree (item);
00840     }
00841 
00842   do_cleanups (cleanup);
00843 }
00844 
00845 /* Submit an event to the gdb thread.  */
00846 static PyObject *
00847 gdbpy_post_event (PyObject *self, PyObject *args)
00848 {
00849   struct gdbpy_event *event;
00850   PyObject *func;
00851   int wakeup;
00852 
00853   if (!PyArg_ParseTuple (args, "O", &func))
00854     return NULL;
00855 
00856   if (!PyCallable_Check (func))
00857     {
00858       PyErr_SetString (PyExc_RuntimeError, 
00859                        _("Posted event is not callable"));
00860       return NULL;
00861     }
00862 
00863   Py_INCREF (func);
00864 
00865   /* From here until the end of the function, we have the GIL, so we
00866      can operate on our global data structures without worrying.  */
00867   wakeup = gdbpy_event_list == NULL;
00868 
00869   event = XNEW (struct gdbpy_event);
00870   event->event = func;
00871   event->next = NULL;
00872   *gdbpy_event_list_end = event;
00873   gdbpy_event_list_end = &event->next;
00874 
00875   /* Wake up gdb when needed.  */
00876   if (wakeup)
00877     {
00878       char c = 'q';             /* Anything. */
00879 
00880       if (serial_write (gdbpy_event_fds[1], &c, 1))
00881         return PyErr_SetFromErrno (PyExc_IOError);
00882     }
00883 
00884   Py_RETURN_NONE;
00885 }
00886 
00887 /* Initialize the Python event handler.  */
00888 static int
00889 gdbpy_initialize_events (void)
00890 {
00891   if (serial_pipe (gdbpy_event_fds) == 0)
00892     {
00893       gdbpy_event_list_end = &gdbpy_event_list;
00894       serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
00895     }
00896 
00897   return 0;
00898 }
00899 
00900 
00901 
00902 static void
00903 before_prompt_hook (const char *current_gdb_prompt)
00904 {
00905   struct cleanup *cleanup;
00906   char *prompt = NULL;
00907 
00908   if (!gdb_python_initialized)
00909     return;
00910 
00911   cleanup = ensure_python_env (get_current_arch (), current_language);
00912 
00913   if (gdb_python_module
00914       && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
00915     {
00916       PyObject *hook;
00917 
00918       hook = PyObject_GetAttrString (gdb_python_module, "prompt_hook");
00919       if (hook == NULL)
00920         goto fail;
00921 
00922       make_cleanup_py_decref (hook);
00923 
00924       if (PyCallable_Check (hook))
00925         {
00926           PyObject *result;
00927           PyObject *current_prompt;
00928 
00929           current_prompt = PyString_FromString (current_gdb_prompt);
00930           if (current_prompt == NULL)
00931             goto fail;
00932 
00933           result = PyObject_CallFunctionObjArgs (hook, current_prompt, NULL);
00934 
00935           Py_DECREF (current_prompt);
00936 
00937           if (result == NULL)
00938             goto fail;
00939 
00940           make_cleanup_py_decref (result);
00941 
00942           /* Return type should be None, or a String.  If it is None,
00943              fall through, we will not set a prompt.  If it is a
00944              string, set  PROMPT.  Anything else, set an exception.  */
00945           if (result != Py_None && ! PyString_Check (result))
00946             {
00947               PyErr_Format (PyExc_RuntimeError,
00948                             _("Return from prompt_hook must " \
00949                               "be either a Python string, or None"));
00950               goto fail;
00951             }
00952 
00953           if (result != Py_None)
00954             {
00955               prompt = python_string_to_host_string (result);
00956 
00957               if (prompt == NULL)
00958                 goto fail;
00959               else
00960                 make_cleanup (xfree, prompt);
00961             }
00962         }
00963     }
00964 
00965   /* If a prompt has been set, PROMPT will not be NULL.  If it is
00966      NULL, do not set the prompt.  */
00967   if (prompt != NULL)
00968     set_prompt (prompt);
00969 
00970   do_cleanups (cleanup);
00971   return;
00972 
00973  fail:
00974   gdbpy_print_stack ();
00975   do_cleanups (cleanup);
00976   return;
00977 }
00978 
00979 
00980 
00981 /* Printing.  */
00982 
00983 /* A python function to write a single string using gdb's filtered
00984    output stream .  The optional keyword STREAM can be used to write
00985    to a particular stream.  The default stream is to gdb_stdout.  */
00986 
00987 static PyObject *
00988 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
00989 {
00990   const char *arg;
00991   static char *keywords[] = {"text", "stream", NULL };
00992   int stream_type = 0;
00993   volatile struct gdb_exception except;
00994   
00995   if (! PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
00996                                      &stream_type))
00997     return NULL;
00998 
00999   TRY_CATCH (except, RETURN_MASK_ALL)
01000     {
01001       switch (stream_type)
01002         {
01003         case 1:
01004           {
01005             fprintf_filtered (gdb_stderr, "%s", arg);
01006             break;
01007           }
01008         case 2:
01009           {
01010             fprintf_filtered (gdb_stdlog, "%s", arg);
01011             break;
01012           }
01013         default:
01014           fprintf_filtered (gdb_stdout, "%s", arg);
01015         }
01016     }
01017   GDB_PY_HANDLE_EXCEPTION (except);
01018      
01019   Py_RETURN_NONE;
01020 }
01021 
01022 /* A python function to flush a gdb stream.  The optional keyword
01023    STREAM can be used to flush a particular stream.  The default stream
01024    is gdb_stdout.  */
01025 
01026 static PyObject *
01027 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
01028 {
01029   static char *keywords[] = {"stream", NULL };
01030   int stream_type = 0;
01031   
01032   if (! PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
01033                                      &stream_type))
01034     return NULL;
01035 
01036   switch (stream_type)
01037     {
01038     case 1:
01039       {
01040         gdb_flush (gdb_stderr);
01041         break;
01042       }
01043     case 2:
01044       {
01045         gdb_flush (gdb_stdlog);
01046         break;
01047       }
01048     default:
01049       gdb_flush (gdb_stdout);
01050     }
01051      
01052   Py_RETURN_NONE;
01053 }
01054 
01055 /* Print a python exception trace, print just a message, or print
01056    nothing and clear the python exception, depending on
01057    gdbpy_should_print_stack.  Only call this if a python exception is
01058    set.  */
01059 void
01060 gdbpy_print_stack (void)
01061 {
01062   volatile struct gdb_exception except;
01063 
01064   /* Print "none", just clear exception.  */
01065   if (gdbpy_should_print_stack == python_excp_none)
01066     {
01067       PyErr_Clear ();
01068     }
01069   /* Print "full" message and backtrace.  */
01070   else if (gdbpy_should_print_stack == python_excp_full)
01071     {
01072       PyErr_Print ();
01073       /* PyErr_Print doesn't necessarily end output with a newline.
01074          This works because Python's stdout/stderr is fed through
01075          printf_filtered.  */
01076       TRY_CATCH (except, RETURN_MASK_ALL)
01077         {
01078           begin_line ();
01079         }
01080     }
01081   /* Print "message", just error print message.  */
01082   else
01083     {
01084       PyObject *ptype, *pvalue, *ptraceback;
01085       char *msg = NULL, *type = NULL;
01086 
01087       PyErr_Fetch (&ptype, &pvalue, &ptraceback);
01088 
01089       /* Fetch the error message contained within ptype, pvalue.  */
01090       msg = gdbpy_exception_to_string (ptype, pvalue);
01091       type = gdbpy_obj_to_string (ptype);
01092 
01093       TRY_CATCH (except, RETURN_MASK_ALL)
01094         {
01095           if (msg == NULL)
01096             {
01097               /* An error occurred computing the string representation of the
01098                  error message.  */
01099               fprintf_filtered (gdb_stderr,
01100                                 _("Error occurred computing Python error" \
01101                                   "message.\n"));
01102             }
01103           else
01104             fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
01105                               type, msg);
01106         }
01107 
01108       Py_XDECREF (ptype);
01109       Py_XDECREF (pvalue);
01110       Py_XDECREF (ptraceback);
01111       xfree (msg);
01112     }
01113 }
01114 
01115 
01116 
01117 /* Return the current Progspace.
01118    There always is one.  */
01119 
01120 static PyObject *
01121 gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
01122 {
01123   PyObject *result;
01124 
01125   result = pspace_to_pspace_object (current_program_space);
01126   if (result)
01127     Py_INCREF (result);
01128   return result;
01129 }
01130 
01131 /* Return a sequence holding all the Progspaces.  */
01132 
01133 static PyObject *
01134 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
01135 {
01136   struct program_space *ps;
01137   PyObject *list;
01138 
01139   list = PyList_New (0);
01140   if (!list)
01141     return NULL;
01142 
01143   ALL_PSPACES (ps)
01144   {
01145     PyObject *item = pspace_to_pspace_object (ps);
01146 
01147     if (!item || PyList_Append (list, item) == -1)
01148       {
01149         Py_DECREF (list);
01150         return NULL;
01151       }
01152   }
01153 
01154   return list;
01155 }
01156 
01157 
01158 
01159 /* The "current" objfile.  This is set when gdb detects that a new
01160    objfile has been loaded.  It is only set for the duration of a call to
01161    source_python_script_for_objfile; it is NULL at other times.  */
01162 static struct objfile *gdbpy_current_objfile;
01163 
01164 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
01165    as Python code.  This does not throw any errors.  If an exception
01166    occurs python will print the traceback and clear the error indicator.  */
01167 
01168 void
01169 source_python_script_for_objfile (struct objfile *objfile, FILE *file,
01170                                   const char *filename)
01171 {
01172   struct cleanup *cleanups;
01173 
01174   if (!gdb_python_initialized)
01175     return;
01176 
01177   cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
01178   gdbpy_current_objfile = objfile;
01179 
01180   python_run_simple_file (file, filename);
01181 
01182   do_cleanups (cleanups);
01183   gdbpy_current_objfile = NULL;
01184 }
01185 
01186 /* Return the current Objfile, or None if there isn't one.  */
01187 
01188 static PyObject *
01189 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
01190 {
01191   PyObject *result;
01192 
01193   if (! gdbpy_current_objfile)
01194     Py_RETURN_NONE;
01195 
01196   result = objfile_to_objfile_object (gdbpy_current_objfile);
01197   if (result)
01198     Py_INCREF (result);
01199   return result;
01200 }
01201 
01202 /* Return a sequence holding all the Objfiles.  */
01203 
01204 static PyObject *
01205 gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
01206 {
01207   struct objfile *objf;
01208   PyObject *list;
01209 
01210   list = PyList_New (0);
01211   if (!list)
01212     return NULL;
01213 
01214   ALL_OBJFILES (objf)
01215   {
01216     PyObject *item = objfile_to_objfile_object (objf);
01217 
01218     if (!item || PyList_Append (list, item) == -1)
01219       {
01220         Py_DECREF (list);
01221         return NULL;
01222       }
01223   }
01224 
01225   return list;
01226 }
01227 
01228 /* Compute the list of active type printers and return it.  The result
01229    of this function can be passed to apply_type_printers, and should
01230    be freed by free_type_printers.  */
01231 
01232 void *
01233 start_type_printers (void)
01234 {
01235   struct cleanup *cleanups;
01236   PyObject *type_module, *func = NULL, *result_obj = NULL;
01237 
01238   if (!gdb_python_initialized)
01239     return NULL;
01240 
01241   cleanups = ensure_python_env (get_current_arch (), current_language);
01242 
01243   type_module = PyImport_ImportModule ("gdb.types");
01244   if (type_module == NULL)
01245     {
01246       gdbpy_print_stack ();
01247       goto done;
01248     }
01249 
01250   func = PyObject_GetAttrString (type_module, "get_type_recognizers");
01251   if (func == NULL)
01252     {
01253       gdbpy_print_stack ();
01254       goto done;
01255     }
01256 
01257   result_obj = PyObject_CallFunctionObjArgs (func, (char *) NULL);
01258   if (result_obj == NULL)
01259     gdbpy_print_stack ();
01260 
01261  done:
01262   Py_XDECREF (type_module);
01263   Py_XDECREF (func);
01264   do_cleanups (cleanups);
01265   return result_obj;
01266 }
01267 
01268 /* If TYPE is recognized by some type printer, return a newly
01269    allocated string holding the type's replacement name.  The caller
01270    is responsible for freeing the string.  Otherwise, return NULL.
01271 
01272    This function has a bit of a funny name, since it actually applies
01273    recognizers, but this seemed clearer given the start_type_printers
01274    and free_type_printers functions.  */
01275 
01276 char *
01277 apply_type_printers (void *printers, struct type *type)
01278 {
01279   struct cleanup *cleanups;
01280   PyObject *type_obj, *type_module = NULL, *func = NULL;
01281   PyObject *result_obj = NULL;
01282   PyObject *printers_obj = printers;
01283   char *result = NULL;
01284 
01285   if (printers_obj == NULL)
01286     return NULL;
01287 
01288   if (!gdb_python_initialized)
01289     return NULL;
01290 
01291   cleanups = ensure_python_env (get_current_arch (), current_language);
01292 
01293   type_obj = type_to_type_object (type);
01294   if (type_obj == NULL)
01295     {
01296       gdbpy_print_stack ();
01297       goto done;
01298     }
01299 
01300   type_module = PyImport_ImportModule ("gdb.types");
01301   if (type_module == NULL)
01302     {
01303       gdbpy_print_stack ();
01304       goto done;
01305     }
01306 
01307   func = PyObject_GetAttrString (type_module, "apply_type_recognizers");
01308   if (func == NULL)
01309     {
01310       gdbpy_print_stack ();
01311       goto done;
01312     }
01313 
01314   result_obj = PyObject_CallFunctionObjArgs (func, printers_obj,
01315                                              type_obj, (char *) NULL);
01316   if (result_obj == NULL)
01317     {
01318       gdbpy_print_stack ();
01319       goto done;
01320     }
01321 
01322   if (result_obj != Py_None)
01323     {
01324       result = python_string_to_host_string (result_obj);
01325       if (result == NULL)
01326         gdbpy_print_stack ();
01327     }
01328 
01329  done:
01330   Py_XDECREF (type_obj);
01331   Py_XDECREF (type_module);
01332   Py_XDECREF (func);
01333   Py_XDECREF (result_obj);
01334   do_cleanups (cleanups);
01335   return result;
01336 }
01337 
01338 /* Free the result of start_type_printers.  */
01339 
01340 void
01341 free_type_printers (void *arg)
01342 {
01343   struct cleanup *cleanups;
01344   PyObject *printers = arg;
01345 
01346   if (printers == NULL)
01347     return;
01348 
01349   if (!gdb_python_initialized)
01350     return;
01351 
01352   cleanups = ensure_python_env (get_current_arch (), current_language);
01353   Py_DECREF (printers);
01354   do_cleanups (cleanups);
01355 }
01356 
01357 #else /* HAVE_PYTHON */
01358 
01359 /* Dummy implementation of the gdb "python-interactive" and "python"
01360    command. */
01361 
01362 static void
01363 python_interactive_command (char *arg, int from_tty)
01364 {
01365   arg = skip_spaces (arg);
01366   if (arg && *arg)
01367     error (_("Python scripting is not supported in this copy of GDB."));
01368   else
01369     {
01370       struct command_line *l = get_command_line (python_control, "");
01371       struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
01372 
01373       execute_control_command_untraced (l);
01374       do_cleanups (cleanups);
01375     }
01376 }
01377 
01378 static void
01379 python_command (char *arg, int from_tty)
01380 {
01381   python_interactive_command (arg, from_tty);
01382 }
01383 
01384 void
01385 eval_python_from_control_command (struct command_line *cmd)
01386 {
01387   error (_("Python scripting is not supported in this copy of GDB."));
01388 }
01389 
01390 void
01391 source_python_script (FILE *file, const char *filename)
01392 {
01393   throw_error (UNSUPPORTED_ERROR,
01394                _("Python scripting is not supported in this copy of GDB."));
01395 }
01396 
01397 int
01398 gdbpy_should_stop (struct breakpoint_object *bp_obj)
01399 {
01400   internal_error (__FILE__, __LINE__,
01401                   _("gdbpy_should_stop called when Python scripting is  " \
01402                     "not supported."));
01403 }
01404 
01405 int
01406 gdbpy_breakpoint_has_py_cond (struct breakpoint_object *bp_obj)
01407 {
01408   internal_error (__FILE__, __LINE__,
01409                   _("gdbpy_breakpoint_has_py_cond called when Python " \
01410                     "scripting is not supported."));
01411 }
01412 
01413 void *
01414 start_type_printers (void)
01415 {
01416   return NULL;
01417 }
01418 
01419 char *
01420 apply_type_printers (void *ignore, struct type *type)
01421 {
01422   return NULL;
01423 }
01424 
01425 void
01426 free_type_printers (void *arg)
01427 {
01428 }
01429 
01430 enum py_bt_status
01431 apply_frame_filter (struct frame_info *frame, int flags,
01432                     enum py_frame_args args_type,
01433                     struct ui_out *out, int frame_low,
01434                     int frame_high)
01435 {
01436   return PY_BT_NO_FILTERS;
01437 }
01438 
01439 #endif /* HAVE_PYTHON */
01440 
01441 
01442 
01443 /* Lists for 'set python' commands.  */
01444 
01445 static struct cmd_list_element *user_set_python_list;
01446 static struct cmd_list_element *user_show_python_list;
01447 
01448 /* Function for use by 'set python' prefix command.  */
01449 
01450 static void
01451 user_set_python (char *args, int from_tty)
01452 {
01453   help_list (user_set_python_list, "set python ", all_commands,
01454              gdb_stdout);
01455 }
01456 
01457 /* Function for use by 'show python' prefix command.  */
01458 
01459 static void
01460 user_show_python (char *args, int from_tty)
01461 {
01462   cmd_show_list (user_show_python_list, from_tty, "");
01463 }
01464 
01465 /* Initialize the Python code.  */
01466 
01467 #ifdef HAVE_PYTHON
01468 
01469 /* This is installed as a final cleanup and cleans up the
01470    interpreter.  This lets Python's 'atexit' work.  */
01471 
01472 static void
01473 finalize_python (void *ignore)
01474 {
01475   /* We don't use ensure_python_env here because if we ever ran the
01476      cleanup, gdb would crash -- because the cleanup calls into the
01477      Python interpreter, which we are about to destroy.  It seems
01478      clearer to make the needed calls explicitly here than to create a
01479      cleanup and then mysteriously discard it.  */
01480   (void) PyGILState_Ensure ();
01481   python_gdbarch = target_gdbarch ();
01482   python_language = current_language;
01483 
01484   Py_Finalize ();
01485 }
01486 #endif
01487 
01488 /* Provide a prototype to silence -Wmissing-prototypes.  */
01489 extern initialize_file_ftype _initialize_python;
01490 
01491 void
01492 _initialize_python (void)
01493 {
01494   char *progname;
01495 #ifdef IS_PY3K
01496   int i;
01497   size_t progsize, count;
01498   char *oldloc;
01499   wchar_t *progname_copy;
01500 #endif
01501 
01502   add_com ("python-interactive", class_obscure,
01503            python_interactive_command,
01504 #ifdef HAVE_PYTHON
01505            _("\
01506 Start an interactive Python prompt.\n\
01507 \n\
01508 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
01509 prompt).\n\
01510 \n\
01511 Alternatively, a single-line Python command can be given as an\n\
01512 argument, and if the command is an expression, the result will be\n\
01513 printed.  For example:\n\
01514 \n\
01515     (gdb) python-interactive 2 + 3\n\
01516     5\n\
01517 ")
01518 #else /* HAVE_PYTHON */
01519            _("\
01520 Start a Python interactive prompt.\n\
01521 \n\
01522 Python scripting is not supported in this copy of GDB.\n\
01523 This command is only a placeholder.")
01524 #endif /* HAVE_PYTHON */
01525            );
01526   add_com_alias ("pi", "python-interactive", class_obscure, 1);
01527 
01528   add_com ("python", class_obscure, python_command,
01529 #ifdef HAVE_PYTHON
01530            _("\
01531 Evaluate a Python command.\n\
01532 \n\
01533 The command can be given as an argument, for instance:\n\
01534 \n\
01535     python print 23\n\
01536 \n\
01537 If no argument is given, the following lines are read and used\n\
01538 as the Python commands.  Type a line containing \"end\" to indicate\n\
01539 the end of the command.")
01540 #else /* HAVE_PYTHON */
01541            _("\
01542 Evaluate a Python command.\n\
01543 \n\
01544 Python scripting is not supported in this copy of GDB.\n\
01545 This command is only a placeholder.")
01546 #endif /* HAVE_PYTHON */
01547            );
01548   add_com_alias ("py", "python", class_obscure, 1);
01549 
01550   /* Add set/show python print-stack.  */
01551   add_prefix_cmd ("python", no_class, user_show_python,
01552                   _("Prefix command for python preference settings."),
01553                   &user_show_python_list, "show python ", 0,
01554                   &showlist);
01555 
01556   add_prefix_cmd ("python", no_class, user_set_python,
01557                   _("Prefix command for python preference settings."),
01558                   &user_set_python_list, "set python ", 0,
01559                   &setlist);
01560 
01561   add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
01562                         &gdbpy_should_print_stack, _("\
01563 Set mode for Python stack dump on error."), _("\
01564 Show the mode of Python stack printing on error."), _("\
01565 none  == no stack or message will be printed.\n\
01566 full == a message and a stack will be printed.\n\
01567 message == an error message without a stack will be printed."),
01568                         NULL, NULL,
01569                         &user_set_python_list,
01570                         &user_show_python_list);
01571 
01572 #ifdef HAVE_PYTHON
01573 #ifdef WITH_PYTHON_PATH
01574   /* Work around problem where python gets confused about where it is,
01575      and then can't find its libraries, etc.
01576      NOTE: Python assumes the following layout:
01577      /foo/bin/python
01578      /foo/lib/pythonX.Y/...
01579      This must be done before calling Py_Initialize.  */
01580   progname = concat (ldirname (python_libdir), SLASH_STRING, "bin",
01581                      SLASH_STRING, "python", NULL);
01582 #ifdef IS_PY3K
01583   oldloc = setlocale (LC_ALL, NULL);
01584   setlocale (LC_ALL, "");
01585   progsize = strlen (progname);
01586   if (progsize == (size_t) -1)
01587     {
01588       fprintf (stderr, "Could not convert python path to string\n");
01589       return;
01590     }
01591   progname_copy = PyMem_Malloc ((progsize + 1) * sizeof (wchar_t));
01592   if (!progname_copy)
01593     {
01594       fprintf (stderr, "out of memory\n");
01595       return;
01596     }
01597   count = mbstowcs (progname_copy, progname, progsize + 1);
01598   if (count == (size_t) -1)
01599     {
01600       fprintf (stderr, "Could not convert python path to string\n");
01601       return;
01602     }
01603   setlocale (LC_ALL, oldloc);
01604 
01605   /* Note that Py_SetProgramName expects the string it is passed to
01606      remain alive for the duration of the program's execution, so
01607      it is not freed after this call.  */
01608   Py_SetProgramName (progname_copy);
01609 #else
01610   Py_SetProgramName (progname);
01611 #endif
01612 #endif
01613 
01614   Py_Initialize ();
01615   PyEval_InitThreads ();
01616 
01617 #ifdef IS_PY3K
01618   gdb_module = PyModule_Create (&GdbModuleDef);
01619   /* Add _gdb module to the list of known built-in modules.  */
01620   _PyImport_FixupBuiltin (gdb_module, "_gdb");
01621 #else
01622   gdb_module = Py_InitModule ("_gdb", GdbMethods);
01623 #endif
01624   if (gdb_module == NULL)
01625     goto fail;
01626 
01627   /* The casts to (char*) are for python 2.4.  */
01628   if (PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version) < 0
01629       || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG",
01630                                      (char*) host_name) < 0
01631       || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
01632                                      (char*) target_name) < 0)
01633     goto fail;
01634 
01635   /* Add stream constants.  */
01636   if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
01637       || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
01638       || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
01639     goto fail;
01640 
01641   gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
01642   if (gdbpy_gdb_error == NULL
01643       || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
01644     goto fail;
01645 
01646   gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
01647                                                gdbpy_gdb_error, NULL);
01648   if (gdbpy_gdb_memory_error == NULL
01649       || gdb_pymodule_addobject (gdb_module, "MemoryError",
01650                                  gdbpy_gdb_memory_error) < 0)
01651     goto fail;
01652 
01653   gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
01654   if (gdbpy_gdberror_exc == NULL
01655       || gdb_pymodule_addobject (gdb_module, "GdbError",
01656                                  gdbpy_gdberror_exc) < 0)
01657     goto fail;
01658 
01659   gdbpy_initialize_gdb_readline ();
01660 
01661   if (gdbpy_initialize_auto_load () < 0
01662       || gdbpy_initialize_values () < 0
01663       || gdbpy_initialize_frames () < 0
01664       || gdbpy_initialize_commands () < 0
01665       || gdbpy_initialize_symbols () < 0
01666       || gdbpy_initialize_symtabs () < 0
01667       || gdbpy_initialize_blocks () < 0
01668       || gdbpy_initialize_functions () < 0
01669       || gdbpy_initialize_parameters () < 0
01670       || gdbpy_initialize_types () < 0
01671       || gdbpy_initialize_pspace () < 0
01672       || gdbpy_initialize_objfile () < 0
01673       || gdbpy_initialize_breakpoints () < 0
01674       || gdbpy_initialize_finishbreakpoints () < 0
01675       || gdbpy_initialize_lazy_string () < 0
01676       || gdbpy_initialize_thread () < 0
01677       || gdbpy_initialize_inferior () < 0
01678       || gdbpy_initialize_events () < 0
01679       || gdbpy_initialize_eventregistry () < 0
01680       || gdbpy_initialize_py_events () < 0
01681       || gdbpy_initialize_event () < 0
01682       || gdbpy_initialize_stop_event () < 0
01683       || gdbpy_initialize_signal_event () < 0
01684       || gdbpy_initialize_breakpoint_event () < 0
01685       || gdbpy_initialize_continue_event () < 0
01686       || gdbpy_initialize_exited_event () < 0
01687       || gdbpy_initialize_thread_event () < 0
01688       || gdbpy_initialize_new_objfile_event ()  < 0
01689       || gdbpy_initialize_arch () < 0)
01690     goto fail;
01691 
01692   observer_attach_before_prompt (before_prompt_hook);
01693 
01694   gdbpy_to_string_cst = PyString_FromString ("to_string");
01695   if (gdbpy_to_string_cst == NULL)
01696     goto fail;
01697   gdbpy_children_cst = PyString_FromString ("children");
01698   if (gdbpy_children_cst == NULL)
01699     goto fail;
01700   gdbpy_display_hint_cst = PyString_FromString ("display_hint");
01701   if (gdbpy_display_hint_cst == NULL)
01702     goto fail;
01703   gdbpy_doc_cst = PyString_FromString ("__doc__");
01704   if (gdbpy_doc_cst == NULL)
01705     goto fail;
01706   gdbpy_enabled_cst = PyString_FromString ("enabled");
01707   if (gdbpy_enabled_cst == NULL)
01708     goto fail;
01709   gdbpy_value_cst = PyString_FromString ("value");
01710   if (gdbpy_value_cst == NULL)
01711     goto fail;
01712 
01713   /* Release the GIL while gdb runs.  */
01714   PyThreadState_Swap (NULL);
01715   PyEval_ReleaseLock ();
01716 
01717   make_final_cleanup (finalize_python, NULL);
01718 
01719   gdb_python_initialized = 1;
01720   return;
01721 
01722  fail:
01723   gdbpy_print_stack ();
01724   /* Do not set 'gdb_python_initialized'.  */
01725   return;
01726 
01727 #endif /* HAVE_PYTHON */
01728 }
01729 
01730 #ifdef HAVE_PYTHON
01731 
01732 /* Perform the remaining python initializations.
01733    These must be done after GDB is at least mostly initialized.
01734    E.g., The "info pretty-printer" command needs the "info" prefix
01735    command installed.  */
01736 
01737 void
01738 finish_python_initialization (void)
01739 {
01740   PyObject *m;
01741   char *gdb_pythondir;
01742   PyObject *sys_path;
01743   struct cleanup *cleanup;
01744 
01745   cleanup = ensure_python_env (get_current_arch (), current_language);
01746 
01747   /* Add the initial data-directory to sys.path.  */
01748 
01749   gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
01750   make_cleanup (xfree, gdb_pythondir);
01751 
01752   sys_path = PySys_GetObject ("path");
01753 
01754   /* If sys.path is not defined yet, define it first.  */
01755   if (!(sys_path && PyList_Check (sys_path)))
01756     {
01757 #ifdef IS_PY3K
01758       PySys_SetPath (L"");
01759 #else
01760       PySys_SetPath ("");
01761 #endif
01762       sys_path = PySys_GetObject ("path");
01763     }
01764   if (sys_path && PyList_Check (sys_path))  
01765     {
01766       PyObject *pythondir;
01767       int err;
01768 
01769       pythondir = PyString_FromString (gdb_pythondir);
01770       if (pythondir == NULL)
01771         goto fail;
01772 
01773       err = PyList_Insert (sys_path, 0, pythondir);
01774       Py_DECREF (pythondir);
01775       if (err)
01776         goto fail;
01777     }
01778   else
01779     goto fail;
01780 
01781   /* Import the gdb module to finish the initialization, and
01782      add it to __main__ for convenience.  */
01783   m = PyImport_AddModule ("__main__");
01784   if (m == NULL)
01785     goto fail;
01786 
01787   gdb_python_module = PyImport_ImportModule ("gdb");
01788   if (gdb_python_module == NULL)
01789     {
01790       gdbpy_print_stack ();
01791       /* This is passed in one call to warning so that blank lines aren't
01792          inserted between each line of text.  */
01793       warning (_("\n"
01794                  "Could not load the Python gdb module from `%s'.\n"
01795                  "Limited Python support is available from the _gdb module.\n"
01796                  "Suggest passing --data-directory=/path/to/gdb/data-directory.\n"),
01797                  gdb_pythondir);
01798       do_cleanups (cleanup);
01799       return;
01800     }
01801 
01802   if (gdb_pymodule_addobject (m, "gdb", gdb_python_module) < 0)
01803     goto fail;
01804 
01805   /* Keep the reference to gdb_python_module since it is in a global
01806      variable.  */
01807 
01808   do_cleanups (cleanup);
01809   return;
01810 
01811  fail:
01812   gdbpy_print_stack ();
01813   warning (_("internal error: Unhandled Python exception"));
01814   do_cleanups (cleanup);
01815 }
01816 
01817 #endif /* HAVE_PYTHON */
01818 
01819 
01820 
01821 #ifdef HAVE_PYTHON
01822 
01823 static PyMethodDef GdbMethods[] =
01824 {
01825   { "history", gdbpy_history, METH_VARARGS,
01826     "Get a value from history" },
01827   { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
01828     "execute (command [, from_tty] [, to_string]) -> [String]\n\
01829 Evaluate command, a string, as a gdb CLI command.  Optionally returns\n\
01830 a Python String containing the output of the command if to_string is\n\
01831 set to True." },
01832   { "parameter", gdbpy_parameter, METH_VARARGS,
01833     "Return a gdb parameter's value" },
01834 
01835   { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
01836     "Return a tuple of all breakpoint objects" },
01837 
01838   { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
01839     "Find the default visualizer for a Value." },
01840 
01841   { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
01842     "Return the current Progspace." },
01843   { "progspaces", gdbpy_progspaces, METH_NOARGS,
01844     "Return a sequence of all progspaces." },
01845 
01846   { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
01847     "Return the current Objfile being loaded, or None." },
01848   { "objfiles", gdbpy_objfiles, METH_NOARGS,
01849     "Return a sequence of all loaded objfiles." },
01850 
01851   { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
01852     "newest_frame () -> gdb.Frame.\n\
01853 Return the newest frame object." },
01854   { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
01855     "selected_frame () -> gdb.Frame.\n\
01856 Return the selected frame object." },
01857   { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
01858     "stop_reason_string (Integer) -> String.\n\
01859 Return a string explaining unwind stop reason." },
01860 
01861   { "lookup_type", (PyCFunction) gdbpy_lookup_type,
01862     METH_VARARGS | METH_KEYWORDS,
01863     "lookup_type (name [, block]) -> type\n\
01864 Return a Type corresponding to the given name." },
01865   { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
01866     METH_VARARGS | METH_KEYWORDS,
01867     "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
01868 Return a tuple with the symbol corresponding to the given name (or None) and\n\
01869 a boolean indicating if name is a field of the current implied argument\n\
01870 `this' (when the current language is object-oriented)." },
01871   { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
01872     METH_VARARGS | METH_KEYWORDS,
01873     "lookup_global_symbol (name [, domain]) -> symbol\n\
01874 Return the symbol corresponding to the given name (or None)." },
01875   { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
01876     "Return the block containing the given pc value, or None." },
01877   { "solib_name", gdbpy_solib_name, METH_VARARGS,
01878     "solib_name (Long) -> String.\n\
01879 Return the name of the shared library holding a given address, or None." },
01880   { "decode_line", gdbpy_decode_line, METH_VARARGS,
01881     "decode_line (String) -> Tuple.  Decode a string argument the way\n\
01882 that 'break' or 'edit' does.  Return a tuple containing two elements.\n\
01883 The first element contains any unparsed portion of the String parameter\n\
01884 (or None if the string was fully parsed).  The second element contains\n\
01885 a tuple that contains all the locations that match, represented as\n\
01886 gdb.Symtab_and_line objects (or None)."},
01887   { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
01888     "parse_and_eval (String) -> Value.\n\
01889 Parse String as an expression, evaluate it, and return the result as a Value."
01890   },
01891   { "find_pc_line", gdbpy_find_pc_line, METH_VARARGS,
01892     "find_pc_line (pc) -> Symtab_and_line.\n\
01893 Return the gdb.Symtab_and_line object corresponding to the pc value." },
01894 
01895   { "post_event", gdbpy_post_event, METH_VARARGS,
01896     "Post an event into gdb's event loop." },
01897 
01898   { "target_charset", gdbpy_target_charset, METH_NOARGS,
01899     "target_charset () -> string.\n\
01900 Return the name of the current target charset." },
01901   { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
01902     "target_wide_charset () -> string.\n\
01903 Return the name of the current target wide charset." },
01904 
01905   { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
01906     "string_to_argv (String) -> Array.\n\
01907 Parse String and return an argv-like array.\n\
01908 Arguments are separate by spaces and may be quoted."
01909   },
01910   { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
01911     "Write a string using gdb's filtered stream." },
01912   { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
01913     "Flush gdb's filtered stdout stream." },
01914   { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
01915     "selected_thread () -> gdb.InferiorThread.\n\
01916 Return the selected thread object." },
01917   { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
01918     "selected_inferior () -> gdb.Inferior.\n\
01919 Return the selected inferior object." },
01920   { "inferiors", gdbpy_inferiors, METH_NOARGS,
01921     "inferiors () -> (gdb.Inferior, ...).\n\
01922 Return a tuple containing all inferiors." },
01923   {NULL, NULL, 0, NULL}
01924 };
01925 
01926 #ifdef IS_PY3K
01927 static struct PyModuleDef GdbModuleDef =
01928 {
01929   PyModuleDef_HEAD_INIT,
01930   "_gdb",
01931   NULL,
01932   -1, 
01933   GdbMethods,
01934   NULL,
01935   NULL,
01936   NULL,
01937   NULL
01938 };
01939 #endif
01940 #endif /* HAVE_PYTHON */
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Defines