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