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