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