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