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