gdb/
[deliverable/binutils-gdb.git] / gdb / python / python.c
CommitLineData
d57a3c85
TJB
1/* General python/gdb code
2
4c38e0a4 3 Copyright (C) 2008, 2009, 2010 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"
d57a3c85
TJB
33
34#include <ctype.h>
35
36/* True if we should print the stack when catching a Python error,
37 false otherwise. */
38static int gdbpy_should_print_stack = 1;
39
40#ifdef HAVE_PYTHON
41
42#include "python.h"
43#include "libiberty.h"
44#include "cli/cli-decode.h"
45#include "charset.h"
46#include "top.h"
cb2e07a6 47#include "solib.h"
d57a3c85 48#include "python-internal.h"
cb2e07a6
PM
49#include "linespec.h"
50#include "source.h"
d57a3c85
TJB
51#include "version.h"
52#include "target.h"
53#include "gdbthread.h"
54
12453b93 55static PyMethodDef GdbMethods[];
d57a3c85
TJB
56
57PyObject *gdb_module;
58
a6bac58e
TT
59/* Some string constants we may wish to use. */
60PyObject *gdbpy_to_string_cst;
61PyObject *gdbpy_children_cst;
62PyObject *gdbpy_display_hint_cst;
d8906c6f 63PyObject *gdbpy_doc_cst;
967cf477 64PyObject *gdbpy_enabled_cst;
d8906c6f 65
07ca107c
DE
66/* The GdbError exception. */
67PyObject *gdbpy_gdberror_exc;
d452c4bc
UW
68
69/* Architecture and language to be used in callbacks from
70 the Python interpreter. */
71struct gdbarch *python_gdbarch;
72const struct language_defn *python_language;
73
74/* Restore global language and architecture and Python GIL state
75 when leaving the Python interpreter. */
76
77struct python_env
78{
79 PyGILState_STATE state;
80 struct gdbarch *gdbarch;
81 const struct language_defn *language;
8dc78533 82 PyObject *error_type, *error_value, *error_traceback;
d452c4bc
UW
83};
84
85static void
86restore_python_env (void *p)
87{
88 struct python_env *env = (struct python_env *)p;
d59b6f6c 89
8dc78533
JK
90 /* Leftover Python error is forbidden by Python Exception Handling. */
91 if (PyErr_Occurred ())
92 {
93 /* This order is similar to the one calling error afterwards. */
94 gdbpy_print_stack ();
95 warning (_("internal error: Unhandled Python exception"));
96 }
97
98 PyErr_Restore (env->error_type, env->error_value, env->error_traceback);
99
d452c4bc
UW
100 PyGILState_Release (env->state);
101 python_gdbarch = env->gdbarch;
102 python_language = env->language;
103 xfree (env);
104}
105
106/* Called before entering the Python interpreter to install the
107 current language and architecture to be used for Python values. */
108
109struct cleanup *
110ensure_python_env (struct gdbarch *gdbarch,
111 const struct language_defn *language)
112{
113 struct python_env *env = xmalloc (sizeof *env);
114
115 env->state = PyGILState_Ensure ();
116 env->gdbarch = python_gdbarch;
117 env->language = python_language;
118
119 python_gdbarch = gdbarch;
120 python_language = language;
121
8dc78533
JK
122 /* Save it and ensure ! PyErr_Occurred () afterwards. */
123 PyErr_Fetch (&env->error_type, &env->error_value, &env->error_traceback);
124
d452c4bc
UW
125 return make_cleanup (restore_python_env, env);
126}
127
128
d57a3c85
TJB
129/* Given a command_line, return a command string suitable for passing
130 to Python. Lines in the string are separated by newlines. The
131 return value is allocated using xmalloc and the caller is
132 responsible for freeing it. */
133
134static char *
135compute_python_string (struct command_line *l)
136{
137 struct command_line *iter;
138 char *script = NULL;
139 int size = 0;
140 int here;
141
142 for (iter = l; iter; iter = iter->next)
143 size += strlen (iter->line) + 1;
144
145 script = xmalloc (size + 1);
146 here = 0;
147 for (iter = l; iter; iter = iter->next)
148 {
149 int len = strlen (iter->line);
d59b6f6c 150
d57a3c85
TJB
151 strcpy (&script[here], iter->line);
152 here += len;
153 script[here++] = '\n';
154 }
155 script[here] = '\0';
156 return script;
157}
158
159/* Take a command line structure representing a 'python' command, and
160 evaluate its body using the Python interpreter. */
161
162void
163eval_python_from_control_command (struct command_line *cmd)
164{
12453b93 165 int ret;
d57a3c85 166 char *script;
ca30a762 167 struct cleanup *cleanup;
d57a3c85
TJB
168
169 if (cmd->body_count != 1)
170 error (_("Invalid \"python\" block structure."));
171
d452c4bc 172 cleanup = ensure_python_env (get_current_arch (), current_language);
ca30a762 173
d57a3c85 174 script = compute_python_string (cmd->body_list[0]);
12453b93 175 ret = PyRun_SimpleString (script);
d57a3c85 176 xfree (script);
12453b93 177 if (ret)
d57a3c85
TJB
178 {
179 gdbpy_print_stack ();
12453b93 180 error (_("Error while executing Python code."));
d57a3c85 181 }
ca30a762
TT
182
183 do_cleanups (cleanup);
d57a3c85
TJB
184}
185
186/* Implementation of the gdb "python" command. */
187
188static void
189python_command (char *arg, int from_tty)
190{
ca30a762 191 struct cleanup *cleanup;
ca30a762 192
d59b6f6c 193 cleanup = ensure_python_env (get_current_arch (), current_language);
d57a3c85
TJB
194 while (arg && *arg && isspace (*arg))
195 ++arg;
196 if (arg && *arg)
197 {
12453b93 198 if (PyRun_SimpleString (arg))
d57a3c85
TJB
199 {
200 gdbpy_print_stack ();
12453b93 201 error (_("Error while executing Python code."));
d57a3c85
TJB
202 }
203 }
204 else
205 {
206 struct command_line *l = get_command_line (python_control, "");
d59b6f6c 207
ca30a762 208 make_cleanup_free_command_lines (&l);
d57a3c85 209 execute_control_command_untraced (l);
d57a3c85 210 }
ca30a762
TT
211
212 do_cleanups (cleanup);
d57a3c85
TJB
213}
214
215\f
216
217/* Transform a gdb parameters's value into a Python value. May return
218 NULL (and set a Python exception) on error. Helper function for
219 get_parameter. */
d7b32ed3
PM
220PyObject *
221gdbpy_parameter_value (enum var_types type, void *var)
d57a3c85 222{
d7b32ed3 223 switch (type)
d57a3c85
TJB
224 {
225 case var_string:
226 case var_string_noescape:
227 case var_optional_filename:
228 case var_filename:
229 case var_enum:
230 {
d7b32ed3 231 char *str = * (char **) var;
d59b6f6c 232
d57a3c85
TJB
233 if (! str)
234 str = "";
235 return PyString_Decode (str, strlen (str), host_charset (), NULL);
236 }
237
238 case var_boolean:
239 {
d7b32ed3 240 if (* (int *) var)
d57a3c85
TJB
241 Py_RETURN_TRUE;
242 else
243 Py_RETURN_FALSE;
244 }
245
246 case var_auto_boolean:
247 {
d7b32ed3 248 enum auto_boolean ab = * (enum auto_boolean *) var;
d59b6f6c 249
d57a3c85
TJB
250 if (ab == AUTO_BOOLEAN_TRUE)
251 Py_RETURN_TRUE;
252 else if (ab == AUTO_BOOLEAN_FALSE)
253 Py_RETURN_FALSE;
254 else
255 Py_RETURN_NONE;
256 }
257
258 case var_integer:
d7b32ed3 259 if ((* (int *) var) == INT_MAX)
d57a3c85
TJB
260 Py_RETURN_NONE;
261 /* Fall through. */
262 case var_zinteger:
d7b32ed3 263 return PyLong_FromLong (* (int *) var);
d57a3c85
TJB
264
265 case var_uinteger:
266 {
d7b32ed3 267 unsigned int val = * (unsigned int *) var;
d59b6f6c 268
d57a3c85
TJB
269 if (val == UINT_MAX)
270 Py_RETURN_NONE;
271 return PyLong_FromUnsignedLong (val);
272 }
273 }
274
044c0f87
PM
275 return PyErr_Format (PyExc_RuntimeError,
276 _("Programmer error: unhandled type."));
d57a3c85
TJB
277}
278
279/* A Python function which returns a gdb parameter's value as a Python
280 value. */
281
d7b32ed3 282PyObject *
8f500870 283gdbpy_parameter (PyObject *self, PyObject *args)
d57a3c85
TJB
284{
285 struct cmd_list_element *alias, *prefix, *cmd;
286 char *arg, *newarg;
cc924cad 287 int found = -1;
d57a3c85
TJB
288 volatile struct gdb_exception except;
289
290 if (! PyArg_ParseTuple (args, "s", &arg))
291 return NULL;
292
293 newarg = concat ("show ", arg, (char *) NULL);
294
295 TRY_CATCH (except, RETURN_MASK_ALL)
296 {
cc924cad 297 found = lookup_cmd_composition (newarg, &alias, &prefix, &cmd);
d57a3c85
TJB
298 }
299 xfree (newarg);
300 GDB_PY_HANDLE_EXCEPTION (except);
cc924cad
TJB
301 if (!found)
302 return PyErr_Format (PyExc_RuntimeError,
044c0f87 303 _("Could not find parameter `%s'."), arg);
d57a3c85
TJB
304
305 if (! cmd->var)
044c0f87
PM
306 return PyErr_Format (PyExc_RuntimeError,
307 _("`%s' is not a parameter."), arg);
d7b32ed3 308 return gdbpy_parameter_value (cmd->var_type, cmd->var);
d57a3c85
TJB
309}
310
f870a310
TT
311/* Wrapper for target_charset. */
312
313static PyObject *
314gdbpy_target_charset (PyObject *self, PyObject *args)
315{
316 const char *cset = target_charset (python_gdbarch);
d59b6f6c 317
f870a310
TT
318 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
319}
320
321/* Wrapper for target_wide_charset. */
322
323static PyObject *
324gdbpy_target_wide_charset (PyObject *self, PyObject *args)
325{
326 const char *cset = target_wide_charset (python_gdbarch);
d59b6f6c 327
f870a310
TT
328 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
329}
330
d57a3c85
TJB
331/* A Python function which evaluates a string using the gdb CLI. */
332
333static PyObject *
bc9f0842 334execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
d57a3c85 335{
f92adf3c 336 char *arg;
bc9f0842
TT
337 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
338 int from_tty, to_string;
d57a3c85 339 volatile struct gdb_exception except;
bc9f0842
TT
340 static char *keywords[] = {"command", "from_tty", "to_string", NULL };
341 char *result = NULL;
d57a3c85 342
bc9f0842
TT
343 if (! PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
344 &PyBool_Type, &from_tty_obj,
345 &PyBool_Type, &to_string_obj))
d57a3c85
TJB
346 return NULL;
347
12453b93
TJB
348 from_tty = 0;
349 if (from_tty_obj)
350 {
bc9f0842 351 int cmp = PyObject_IsTrue (from_tty_obj);
12453b93 352 if (cmp < 0)
bc9f0842 353 return NULL;
12453b93
TJB
354 from_tty = cmp;
355 }
356
bc9f0842
TT
357 to_string = 0;
358 if (to_string_obj)
359 {
360 int cmp = PyObject_IsTrue (to_string_obj);
361 if (cmp < 0)
362 return NULL;
363 to_string = cmp;
364 }
365
d57a3c85
TJB
366 TRY_CATCH (except, RETURN_MASK_ALL)
367 {
86c6265d
TT
368 /* Copy the argument text in case the command modifies it. */
369 char *copy = xstrdup (arg);
370 struct cleanup *cleanup = make_cleanup (xfree, copy);
bc9f0842
TT
371
372 if (to_string)
5da1313b
JK
373 result = execute_command_to_string (copy, from_tty);
374 else
bc9f0842 375 {
5da1313b
JK
376 result = NULL;
377 execute_command (copy, from_tty);
bc9f0842 378 }
d59b6f6c 379
86c6265d 380 do_cleanups (cleanup);
d57a3c85
TJB
381 }
382 GDB_PY_HANDLE_EXCEPTION (except);
383
347bddb7
PA
384 /* Do any commands attached to breakpoint we stopped at. */
385 bpstat_do_actions ();
d57a3c85 386
bc9f0842
TT
387 if (result)
388 {
389 PyObject *r = PyString_FromString (result);
390 xfree (result);
391 return r;
392 }
d57a3c85
TJB
393 Py_RETURN_NONE;
394}
395
cb2e07a6
PM
396/* Implementation of gdb.solib_name (Long) -> String.
397 Returns the name of the shared library holding a given address, or None. */
398
399static PyObject *
400gdbpy_solib_name (PyObject *self, PyObject *args)
401{
402 char *soname;
403 PyObject *str_obj;
404#ifdef PY_LONG_LONG
405 unsigned PY_LONG_LONG pc;
76d8b686
KW
406 /* To be compatible with Python 2.4 the format strings are not const. */
407 char *format = "K";
cb2e07a6
PM
408#else
409 unsigned long pc;
76d8b686 410 char *format = "k";
cb2e07a6
PM
411#endif
412
413 if (!PyArg_ParseTuple (args, format, &pc))
414 return NULL;
415
416 soname = solib_name_from_address (current_program_space, pc);
417 if (soname)
418 str_obj = PyString_Decode (soname, strlen (soname), host_charset (), NULL);
419 else
420 {
421 str_obj = Py_None;
422 Py_INCREF (Py_None);
423 }
424
425 return str_obj;
426}
427
428/* A Python function which is a wrapper for decode_line_1. */
429
430static PyObject *
431gdbpy_decode_line (PyObject *self, PyObject *args)
432{
433 struct symtabs_and_lines sals = { NULL, 0 }; /* Initialize to appease gcc. */
434 struct symtab_and_line sal;
435 char *arg = NULL;
436 char *copy = NULL;
437 struct cleanup *cleanups;
438 PyObject *result = NULL;
439 PyObject *return_result = NULL;
440 PyObject *unparsed = NULL;
441 volatile struct gdb_exception except;
442
443 if (! PyArg_ParseTuple (args, "|s", &arg))
444 return NULL;
445
446 cleanups = ensure_python_env (get_current_arch (), current_language);
447
448 TRY_CATCH (except, RETURN_MASK_ALL)
449 {
450 if (arg)
451 {
452 arg = xstrdup (arg);
453 make_cleanup (xfree, arg);
454 copy = arg;
455 sals = decode_line_1 (&copy, 0, 0, 0, 0, 0);
456 make_cleanup (xfree, sals.sals);
457 }
458 else
459 {
460 set_default_source_symtab_and_line ();
461 sal = get_current_source_symtab_and_line ();
462 sals.sals = &sal;
463 sals.nelts = 1;
464 }
465 }
466 if (except.reason < 0)
467 {
468 do_cleanups (cleanups);
469 /* We know this will always throw. */
470 GDB_PY_HANDLE_EXCEPTION (except);
471 }
472
473 if (sals.nelts)
474 {
475 int i;
476
477 result = PyTuple_New (sals.nelts);
478 if (! result)
479 goto error;
480 for (i = 0; i < sals.nelts; ++i)
481 {
482 PyObject *obj;
483 char *str;
484
485 obj = symtab_and_line_to_sal_object (sals.sals[i]);
486 if (! obj)
487 {
488 Py_DECREF (result);
489 goto error;
490 }
491
492 PyTuple_SetItem (result, i, obj);
493 }
494 }
495 else
496 {
497 result = Py_None;
498 Py_INCREF (Py_None);
499 }
500
501 return_result = PyTuple_New (2);
502 if (! return_result)
503 {
504 Py_DECREF (result);
505 goto error;
506 }
507
508 if (copy && strlen (copy) > 0)
509 unparsed = PyString_FromString (copy);
510 else
511 {
512 unparsed = Py_None;
513 Py_INCREF (Py_None);
514 }
515
516 PyTuple_SetItem (return_result, 0, unparsed);
517 PyTuple_SetItem (return_result, 1, result);
518
519 do_cleanups (cleanups);
520
521 return return_result;
522
523 error:
524 do_cleanups (cleanups);
525 return NULL;
526}
527
57a1d736
TT
528/* Parse a string and evaluate it as an expression. */
529static PyObject *
530gdbpy_parse_and_eval (PyObject *self, PyObject *args)
531{
532 char *expr_str;
533 struct value *result = NULL;
534 volatile struct gdb_exception except;
535
536 if (!PyArg_ParseTuple (args, "s", &expr_str))
537 return NULL;
538
539 TRY_CATCH (except, RETURN_MASK_ALL)
540 {
541 result = parse_and_eval (expr_str);
542 }
543 GDB_PY_HANDLE_EXCEPTION (except);
544
545 return value_to_value_object (result);
546}
547
973817a3 548/* Read a file as Python code. STREAM is the input file; FILE is the
3f7b2faa
DE
549 name of the file.
550 STREAM is not closed, that is the caller's responsibility. */
973817a3
JB
551
552void
3f7b2faa 553source_python_script (FILE *stream, const char *file)
973817a3 554{
eb5cda86 555 struct cleanup *cleanup;
973817a3 556
eb5cda86 557 cleanup = ensure_python_env (get_current_arch (), current_language);
973817a3 558
3a1d4620
DE
559 /* Note: If an exception occurs python will print the traceback and
560 clear the error indicator. */
973817a3
JB
561 PyRun_SimpleFile (stream, file);
562
eb5cda86 563 do_cleanups (cleanup);
973817a3
JB
564}
565
d57a3c85
TJB
566\f
567
ca5c20b6
PM
568/* Posting and handling events. */
569
570/* A single event. */
571struct gdbpy_event
572{
573 /* The Python event. This is just a callable object. */
574 PyObject *event;
575 /* The next event. */
576 struct gdbpy_event *next;
577};
578
579/* All pending events. */
580static struct gdbpy_event *gdbpy_event_list;
581/* The final link of the event list. */
582static struct gdbpy_event **gdbpy_event_list_end;
583
584/* We use a file handler, and not an async handler, so that we can
585 wake up the main thread even when it is blocked in poll(). */
4a532131 586static struct serial *gdbpy_event_fds[2];
ca5c20b6
PM
587
588/* The file handler callback. This reads from the internal pipe, and
589 then processes the Python event queue. This will always be run in
590 the main gdb thread. */
4a532131 591
ca5c20b6 592static void
4a532131 593gdbpy_run_events (struct serial *scb, void *context)
ca5c20b6
PM
594{
595 struct cleanup *cleanup;
ca5c20b6
PM
596 int r;
597
598 cleanup = ensure_python_env (get_current_arch (), current_language);
599
4a532131
PA
600 /* Flush the fd. Do this before flushing the events list, so that
601 any new event post afterwards is sure to re-awake the event
602 loop. */
603 while (serial_readchar (gdbpy_event_fds[0], 0) >= 0)
604 ;
ca5c20b6
PM
605
606 while (gdbpy_event_list)
607 {
608 /* Dispatching the event might push a new element onto the event
609 loop, so we update here "atomically enough". */
610 struct gdbpy_event *item = gdbpy_event_list;
611 gdbpy_event_list = gdbpy_event_list->next;
612 if (gdbpy_event_list == NULL)
613 gdbpy_event_list_end = &gdbpy_event_list;
614
615 /* Ignore errors. */
616 if (PyObject_CallObject (item->event, NULL) == NULL)
617 PyErr_Clear ();
618
619 Py_DECREF (item->event);
620 xfree (item);
621 }
622
623 do_cleanups (cleanup);
624}
625
626/* Submit an event to the gdb thread. */
627static PyObject *
628gdbpy_post_event (PyObject *self, PyObject *args)
629{
630 struct gdbpy_event *event;
631 PyObject *func;
632 int wakeup;
633
634 if (!PyArg_ParseTuple (args, "O", &func))
635 return NULL;
636
637 if (!PyCallable_Check (func))
638 {
639 PyErr_SetString (PyExc_RuntimeError,
640 _("Posted event is not callable"));
641 return NULL;
642 }
643
644 Py_INCREF (func);
645
646 /* From here until the end of the function, we have the GIL, so we
647 can operate on our global data structures without worrying. */
648 wakeup = gdbpy_event_list == NULL;
649
650 event = XNEW (struct gdbpy_event);
651 event->event = func;
652 event->next = NULL;
653 *gdbpy_event_list_end = event;
654 gdbpy_event_list_end = &event->next;
655
656 /* Wake up gdb when needed. */
657 if (wakeup)
658 {
659 char c = 'q'; /* Anything. */
4a532131
PA
660
661 if (serial_write (gdbpy_event_fds[1], &c, 1))
ca5c20b6
PM
662 return PyErr_SetFromErrno (PyExc_IOError);
663 }
664
665 Py_RETURN_NONE;
666}
667
668/* Initialize the Python event handler. */
669static void
670gdbpy_initialize_events (void)
671{
4a532131 672 if (serial_pipe (gdbpy_event_fds) == 0)
ca5c20b6
PM
673 {
674 gdbpy_event_list_end = &gdbpy_event_list;
4a532131 675 serial_async (gdbpy_event_fds[0], gdbpy_run_events, NULL);
ca5c20b6
PM
676 }
677}
678
d57a3c85
TJB
679/* Printing. */
680
681/* A python function to write a single string using gdb's filtered
682 output stream. */
683static PyObject *
684gdbpy_write (PyObject *self, PyObject *args)
685{
686 char *arg;
d59b6f6c 687
d57a3c85
TJB
688 if (! PyArg_ParseTuple (args, "s", &arg))
689 return NULL;
690 printf_filtered ("%s", arg);
691 Py_RETURN_NONE;
692}
693
694/* A python function to flush gdb's filtered output stream. */
695static PyObject *
696gdbpy_flush (PyObject *self, PyObject *args)
697{
698 gdb_flush (gdb_stdout);
699 Py_RETURN_NONE;
700}
701
702/* Print a python exception trace, or print nothing and clear the
703 python exception, depending on gdbpy_should_print_stack. Only call
704 this if a python exception is set. */
705void
706gdbpy_print_stack (void)
707{
708 if (gdbpy_should_print_stack)
0bf0f8c4
DE
709 {
710 PyErr_Print ();
711 /* PyErr_Print doesn't necessarily end output with a newline.
712 This works because Python's stdout/stderr is fed through
713 printf_filtered. */
714 begin_line ();
715 }
d57a3c85
TJB
716 else
717 PyErr_Clear ();
718}
719
89c73ade
TT
720\f
721
fa33c3cd
DE
722/* Return the current Progspace.
723 There always is one. */
724
725static PyObject *
726gdbpy_get_current_progspace (PyObject *unused1, PyObject *unused2)
727{
728 PyObject *result;
729
730 result = pspace_to_pspace_object (current_program_space);
731 if (result)
732 Py_INCREF (result);
733 return result;
734}
735
736/* Return a sequence holding all the Progspaces. */
737
738static PyObject *
739gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
740{
741 struct program_space *ps;
742 PyObject *list;
743
744 list = PyList_New (0);
745 if (!list)
746 return NULL;
747
748 ALL_PSPACES (ps)
749 {
750 PyObject *item = pspace_to_pspace_object (ps);
d59b6f6c 751
fa33c3cd
DE
752 if (!item || PyList_Append (list, item) == -1)
753 {
754 Py_DECREF (list);
755 return NULL;
756 }
757 }
758
759 return list;
760}
761
762\f
763
89c73ade 764/* The "current" objfile. This is set when gdb detects that a new
8a1ea21f
DE
765 objfile has been loaded. It is only set for the duration of a call to
766 source_python_script_for_objfile; it is NULL at other times. */
89c73ade
TT
767static struct objfile *gdbpy_current_objfile;
768
8a1ea21f
DE
769/* Set the current objfile to OBJFILE and then read STREAM,FILE as
770 Python code. */
89c73ade 771
8a1ea21f
DE
772void
773source_python_script_for_objfile (struct objfile *objfile,
774 FILE *stream, const char *file)
89c73ade 775{
89c73ade
TT
776 struct cleanup *cleanups;
777
d452c4bc 778 cleanups = ensure_python_env (get_objfile_arch (objfile), current_language);
89c73ade
TT
779 gdbpy_current_objfile = objfile;
780
3a1d4620
DE
781 /* Note: If an exception occurs python will print the traceback and
782 clear the error indicator. */
783 PyRun_SimpleFile (stream, file);
89c73ade
TT
784
785 do_cleanups (cleanups);
786 gdbpy_current_objfile = NULL;
89c73ade
TT
787}
788
789/* Return the current Objfile, or None if there isn't one. */
8a1ea21f 790
89c73ade
TT
791static PyObject *
792gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
793{
794 PyObject *result;
795
796 if (! gdbpy_current_objfile)
797 Py_RETURN_NONE;
798
799 result = objfile_to_objfile_object (gdbpy_current_objfile);
800 if (result)
801 Py_INCREF (result);
802 return result;
803}
804
805/* Return a sequence holding all the Objfiles. */
fa33c3cd 806
89c73ade
TT
807static PyObject *
808gdbpy_objfiles (PyObject *unused1, PyObject *unused2)
809{
810 struct objfile *objf;
811 PyObject *list;
812
813 list = PyList_New (0);
814 if (!list)
815 return NULL;
816
817 ALL_OBJFILES (objf)
818 {
819 PyObject *item = objfile_to_objfile_object (objf);
d59b6f6c 820
89c73ade
TT
821 if (!item || PyList_Append (list, item) == -1)
822 {
823 Py_DECREF (list);
824 return NULL;
825 }
826 }
827
828 return list;
829}
830
d57a3c85
TJB
831#else /* HAVE_PYTHON */
832
833/* Dummy implementation of the gdb "python" command. */
834
835static void
836python_command (char *arg, int from_tty)
837{
838 while (arg && *arg && isspace (*arg))
839 ++arg;
840 if (arg && *arg)
841 error (_("Python scripting is not supported in this copy of GDB."));
842 else
843 {
844 struct command_line *l = get_command_line (python_control, "");
845 struct cleanup *cleanups = make_cleanup_free_command_lines (&l);
d59b6f6c 846
d57a3c85
TJB
847 execute_control_command_untraced (l);
848 do_cleanups (cleanups);
849 }
850}
851
852void
853eval_python_from_control_command (struct command_line *cmd)
854{
855 error (_("Python scripting is not supported in this copy of GDB."));
856}
857
973817a3 858void
3f7b2faa 859source_python_script (FILE *stream, const char *file)
973817a3 860{
973817a3
JB
861 throw_error (UNSUPPORTED_ERROR,
862 _("Python scripting is not supported in this copy of GDB."));
863}
864
d57a3c85
TJB
865#endif /* HAVE_PYTHON */
866
867\f
868
869/* Lists for 'maint set python' commands. */
870
8a1ea21f
DE
871struct cmd_list_element *set_python_list;
872struct cmd_list_element *show_python_list;
d57a3c85
TJB
873
874/* Function for use by 'maint set python' prefix command. */
875
876static void
877set_python (char *args, int from_tty)
878{
879 help_list (set_python_list, "maintenance set python ", -1, gdb_stdout);
880}
881
882/* Function for use by 'maint show python' prefix command. */
883
884static void
885show_python (char *args, int from_tty)
886{
887 cmd_show_list (show_python_list, from_tty, "");
888}
889
890/* Initialize the Python code. */
891
2c0b251b
PA
892/* Provide a prototype to silence -Wmissing-prototypes. */
893extern initialize_file_ftype _initialize_python;
894
d57a3c85
TJB
895void
896_initialize_python (void)
897{
898 add_com ("python", class_obscure, python_command,
899#ifdef HAVE_PYTHON
900 _("\
901Evaluate a Python command.\n\
902\n\
903The command can be given as an argument, for instance:\n\
904\n\
905 python print 23\n\
906\n\
907If no argument is given, the following lines are read and used\n\
908as the Python commands. Type a line containing \"end\" to indicate\n\
909the end of the command.")
910#else /* HAVE_PYTHON */
911 _("\
912Evaluate a Python command.\n\
913\n\
914Python scripting is not supported in this copy of GDB.\n\
915This command is only a placeholder.")
916#endif /* HAVE_PYTHON */
917 );
918
919 add_prefix_cmd ("python", no_class, show_python,
920 _("Prefix command for python maintenance settings."),
509238d6 921 &show_python_list, "maintenance show python ", 0,
d57a3c85
TJB
922 &maintenance_show_cmdlist);
923 add_prefix_cmd ("python", no_class, set_python,
924 _("Prefix command for python maintenance settings."),
509238d6 925 &set_python_list, "maintenance set python ", 0,
d57a3c85
TJB
926 &maintenance_set_cmdlist);
927
928 add_setshow_boolean_cmd ("print-stack", class_maintenance,
929 &gdbpy_should_print_stack, _("\
930Enable or disable printing of Python stack dump on error."), _("\
931Show whether Python stack will be printed on error."), _("\
932Enables or disables printing of Python stack traces."),
933 NULL, NULL,
934 &set_python_list,
935 &show_python_list);
936
937#ifdef HAVE_PYTHON
0c4a4063
DE
938#ifdef WITH_PYTHON_PATH
939 /* Work around problem where python gets confused about where it is,
940 and then can't find its libraries, etc.
941 NOTE: Python assumes the following layout:
942 /foo/bin/python
943 /foo/lib/pythonX.Y/...
944 This must be done before calling Py_Initialize. */
945 Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
946 SLASH_STRING, "python", NULL));
947#endif
948
d57a3c85 949 Py_Initialize ();
ca30a762 950 PyEval_InitThreads ();
d57a3c85
TJB
951
952 gdb_module = Py_InitModule ("gdb", GdbMethods);
953
954 /* The casts to (char*) are for python 2.4. */
955 PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
956 PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", (char*) host_name);
957 PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG", (char*) target_name);
f17618ea
DE
958
959 /* gdb.parameter ("data-directory") doesn't necessarily exist when the python
960 script below is run (depending on order of _initialize_* functions).
961 Define the initial value of gdb.PYTHONDIR here. */
b14285f6
JB
962 {
963 char *gdb_pythondir;
964
965 gdb_pythondir = concat (gdb_datadir, SLASH_STRING, "python", NULL);
966 PyModule_AddStringConstant (gdb_module, "PYTHONDIR", gdb_pythondir);
967 xfree (gdb_pythondir);
968 }
d57a3c85 969
07ca107c
DE
970 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
971 PyModule_AddObject (gdb_module, "GdbError", gdbpy_gdberror_exc);
972
8a1ea21f 973 gdbpy_initialize_auto_load ();
a08702d6 974 gdbpy_initialize_values ();
f8f6f20b 975 gdbpy_initialize_frames ();
d8906c6f 976 gdbpy_initialize_commands ();
f3e9a817
PM
977 gdbpy_initialize_symbols ();
978 gdbpy_initialize_symtabs ();
979 gdbpy_initialize_blocks ();
bc3b79fd 980 gdbpy_initialize_functions ();
d7b32ed3 981 gdbpy_initialize_parameters ();
2c74e833 982 gdbpy_initialize_types ();
fa33c3cd 983 gdbpy_initialize_pspace ();
89c73ade 984 gdbpy_initialize_objfile ();
adc36818 985 gdbpy_initialize_breakpoints ();
be759fcf 986 gdbpy_initialize_lazy_string ();
595939de
PM
987 gdbpy_initialize_thread ();
988 gdbpy_initialize_inferior ();
ca5c20b6 989 gdbpy_initialize_events ();
a08702d6 990
d57a3c85 991 PyRun_SimpleString ("import gdb");
a6bac58e 992 PyRun_SimpleString ("gdb.pretty_printers = []");
d57a3c85 993
a6bac58e
TT
994 gdbpy_to_string_cst = PyString_FromString ("to_string");
995 gdbpy_children_cst = PyString_FromString ("children");
996 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
d8906c6f 997 gdbpy_doc_cst = PyString_FromString ("__doc__");
967cf477 998 gdbpy_enabled_cst = PyString_FromString ("enabled");
d8906c6f 999
f17618ea
DE
1000 /* Remaining initialization is done in Python.
1001 - create a couple objects which are used for Python's stdout and stderr
1002 - provide function GdbSetPythonDirectory */
1003
d57a3c85 1004 PyRun_SimpleString ("\
f17618ea 1005import os\n\
d57a3c85 1006import sys\n\
f17618ea 1007\n\
d57a3c85
TJB
1008class GdbOutputFile:\n\
1009 def close(self):\n\
1010 # Do nothing.\n\
1011 return None\n\
1012\n\
1013 def isatty(self):\n\
1014 return False\n\
1015\n\
1016 def write(self, s):\n\
1017 gdb.write(s)\n\
1018\n\
1019 def writelines(self, iterable):\n\
1020 for line in iterable:\n\
1021 self.write(line)\n\
1022\n\
1023 def flush(self):\n\
1024 gdb.flush()\n\
1025\n\
1026sys.stderr = GdbOutputFile()\n\
1027sys.stdout = GdbOutputFile()\n\
b14285f6 1028\n\
f17618ea
DE
1029# Ideally this would live in the gdb module, but it's intentionally written\n\
1030# in python, and we need this to bootstrap the gdb module.\n\
1031\n\
1032def GdbSetPythonDirectory (dir):\n\
1033 \"Set gdb.PYTHONDIR and update sys.path,etc.\"\n\
1034 old_dir = gdb.PYTHONDIR\n\
1035 gdb.PYTHONDIR = dir\n\
1036 # GDB's python scripts are stored inside gdb.PYTHONDIR. So insert\n\
1037 # that directory name at the start of sys.path to allow the Python\n\
1038 # interpreter to find them.\n\
1039 if old_dir in sys.path:\n\
1040 sys.path.remove (old_dir)\n\
1041 sys.path.insert (0, gdb.PYTHONDIR)\n\
1042\n\
1043 # Tell python where to find submodules of gdb.\n\
1044 gdb.__path__ = [gdb.PYTHONDIR + '/gdb']\n\
1045\n\
1046 # The gdb module is implemented in C rather than in Python. As a result,\n\
1047 # the associated __init.py__ script is not not executed by default when\n\
1048 # the gdb module gets imported. Execute that script manually if it\n\
1049 # exists.\n\
1050 ipy = gdb.PYTHONDIR + '/gdb/__init__.py'\n\
1051 if os.path.exists (ipy):\n\
1052 execfile (ipy)\n\
b14285f6 1053\n\
f17618ea
DE
1054# Install the default gdb.PYTHONDIR.\n\
1055GdbSetPythonDirectory (gdb.PYTHONDIR)\n\
d57a3c85 1056");
ca30a762
TT
1057
1058 /* Release the GIL while gdb runs. */
1059 PyThreadState_Swap (NULL);
1060 PyEval_ReleaseLock ();
1061
d57a3c85
TJB
1062#endif /* HAVE_PYTHON */
1063}
12453b93
TJB
1064
1065\f
1066
1067#if HAVE_PYTHON
1068
1069static PyMethodDef GdbMethods[] =
1070{
1071 { "history", gdbpy_history, METH_VARARGS,
1072 "Get a value from history" },
bc9f0842 1073 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
12453b93 1074 "Execute a gdb command" },
8f500870 1075 { "parameter", gdbpy_parameter, METH_VARARGS,
12453b93
TJB
1076 "Return a gdb parameter's value" },
1077
adc36818
PM
1078 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
1079 "Return a tuple of all breakpoint objects" },
1080
b6313243
TT
1081 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
1082 "Find the default visualizer for a Value." },
1083
fa33c3cd
DE
1084 { "current_progspace", gdbpy_get_current_progspace, METH_NOARGS,
1085 "Return the current Progspace." },
1086 { "progspaces", gdbpy_progspaces, METH_NOARGS,
1087 "Return a sequence of all progspaces." },
1088
89c73ade
TT
1089 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
1090 "Return the current Objfile being loaded, or None." },
1091 { "objfiles", gdbpy_objfiles, METH_NOARGS,
1092 "Return a sequence of all loaded objfiles." },
1093
f8f6f20b
TJB
1094 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
1095 "selected_frame () -> gdb.Frame.\n\
1096Return the selected frame object." },
1097 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
1098 "stop_reason_string (Integer) -> String.\n\
1099Return a string explaining unwind stop reason." },
1100
2c74e833
TT
1101 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
1102 METH_VARARGS | METH_KEYWORDS,
1103 "lookup_type (name [, block]) -> type\n\
1104Return a Type corresponding to the given name." },
f3e9a817
PM
1105 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
1106 METH_VARARGS | METH_KEYWORDS,
1107 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
1108Return a tuple with the symbol corresponding to the given name (or None) and\n\
1109a boolean indicating if name is a field of the current implied argument\n\
1110`this' (when the current language is object-oriented)." },
1111 { "block_for_pc", gdbpy_block_for_pc, METH_VARARGS,
1112 "Return the block containing the given pc value, or None." },
cb2e07a6
PM
1113 { "solib_name", gdbpy_solib_name, METH_VARARGS,
1114 "solib_name (Long) -> String.\n\
1115Return the name of the shared library holding a given address, or None." },
1116 { "decode_line", gdbpy_decode_line, METH_VARARGS,
1117 "decode_line (String) -> Tuple. Decode a string argument the way\n\
1118that 'break' or 'edit' does. Return a tuple containing two elements.\n\
1119The first element contains any unparsed portion of the String parameter\n\
1120(or None if the string was fully parsed). The second element contains\n\
1121a tuple that contains all the locations that match, represented as\n\
1122gdb.Symtab_and_line objects (or None)."},
57a1d736
TT
1123 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
1124 "parse_and_eval (String) -> Value.\n\
1125Parse String as an expression, evaluate it, and return the result as a Value."
1126 },
1127
ca5c20b6
PM
1128 { "post_event", gdbpy_post_event, METH_VARARGS,
1129 "Post an event into gdb's event loop." },
1130
f870a310
TT
1131 { "target_charset", gdbpy_target_charset, METH_NOARGS,
1132 "target_charset () -> string.\n\
1133Return the name of the current target charset." },
1134 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
1135 "target_wide_charset () -> string.\n\
1136Return the name of the current target wide charset." },
1137
07ca107c
DE
1138 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
1139 "string_to_argv (String) -> Array.\n\
1140Parse String and return an argv-like array.\n\
1141Arguments are separate by spaces and may be quoted."
1142 },
1143
12453b93
TJB
1144 { "write", gdbpy_write, METH_VARARGS,
1145 "Write a string using gdb's filtered stream." },
1146 { "flush", gdbpy_flush, METH_NOARGS,
1147 "Flush gdb's filtered stdout stream." },
595939de
PM
1148 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
1149 "selected_thread () -> gdb.InferiorThread.\n\
1150Return the selected thread object." },
1151 { "inferiors", gdbpy_inferiors, METH_NOARGS,
1152 "inferiors () -> (gdb.Inferior, ...).\n\
1153Return a tuple containing all inferiors." },
12453b93
TJB
1154 {NULL, NULL, 0, NULL}
1155};
1156
1157#endif /* HAVE_PYTHON */
This page took 0.309009 seconds and 4 git commands to generate.