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