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