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