* [PATCH] Python 3 support, part 1 (non-testsuite part)
@ 2012-11-12 16:06 Paul_Koning
2012-11-12 20:43 ` Tom Tromey
0 siblings, 1 reply; 16+ messages in thread
From: Paul_Koning @ 2012-11-12 16:06 UTC (permalink / raw)
To: gdb-patches
The attached set of patches updates the Python scripting support in GDB to add Python 3 to the existing Python 2 support.
The majority of the changes are actually in the test suite. I'll send the changes in two parts (base code then testsuite) because the patch is pretty long.
In the C code for Python support, the main changes are:
1. Type objects have a PyVarObject header, and because of the syntax changes in the underlying macros in Python 3, you need a PyVarObject_HEAD_INIT macro to initialize those. For the same reason, calls to the tp_free method need to go through a PyObject * pointer, not a type object pointer.
2. Python 3 has only long integers and unicode strings, called "int" and "str" in Python code but still accessed by PyLong* and PyUnicode* API functions.
Most of these changes are acceptable for Python 2 as well. The ones that need to be different between the two versions are conditional on IS_PY3K (as suggested in the Porting Python 2 to Python 3 manual from python.org).
Tested on Linux with Python version 2.4, 2.6, 2.7, 3.2, and 3.3. No regressions on any of the tests.
Ok to commit?
paul
2012-11-12 Paul Koning <paul_koning@dell.com>
Add support for Python 3.
* varobj.c (value_get_print_value): Use
python_string_to_target_string.
* python/py-block.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
* python/py-breakpoint.c: Ditto.
* python/py-cmd.c: Ditto.
* python/py-event.c: Ditto.
* python/py-event.h: Ditto.
* python/py-evtregistry.c: Ditto.
* python/py-finishbreakpoint.c: Ditto.
* python/py-frame.c: Ditto.
* python/py-function.c: Ditto.
* python/py-infthread.c: Ditto.
* python/py-lazy-string.c: Ditto.
* python/py-progspace.c: Ditto.
* /python/py-symbol.c: Ditto.
* python/py-evts.c: (gdbpy_initialize_py_events): Add module
initialization for Python 3.
* python/py-inferior.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
(infpy_read_memory): Return memoryview object if Python 3.
(infpy_write_memory): Use "s*" operand parsing code for Python 3.
(infpy_search_memory): Ditto.
(get_buffer): New function for Python 3.
* python/py-objfile.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
(objfpy_dealloc): Use PyObject pointer to call tp_free.
* python/py-param.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
(get_attr): Use PyUnicode_CompareWithASCIIString if Python 3.
(set_attr): Ditto.
* python/py-prettyprint.c (print_string_repr): use PyBytes methods
instead of PyString methods if Python 3.
(print_children): Skip push_dummy_python_frame call if Python 3.
* python/py-symtab.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
(salpy_dealloc): Use PyObject pointer to call tp_free.
* python/py-type.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
(field_dealloc): Use PyObject pointer to call tp_free.
(typy_dealloc): Ditto.
(type_object_as_number): Adjust struct initializations for
differences in layout for Python 2 vs. Python 3.
* python/py-utils.c (python_string_to_unicode): Omit non-Unicode
string case for Python 3.
(unicode_to_encoded_python_string): Shorten code (no functional
change).
(python_string_to_target_python_string): Comment that in Python 3
returned value is a Python "bytes" type.
(gdbpy_is_string): Omit non-Unicode string check in Python 3.
(gdb_py_object_from_longest): Omit non-long integer case in Python
3.
(gdb_py_object_from_ulongest): Ditto.
* python/py-value.c: Use PyVarObject_HEAD_INIT in initialization
of type objects.
(valpy_dealloc): Use PyObject pointer to call tp_free.
(valpy_int): Omit function if Python 3.
(convert_value_from_python): Use "%S" format (Python object as a
string) if Python 3.
(value_object_as_number): Adjust struct initializations for
differences in layout for Python 2 vs. Python 3.
* python/python-config.py: Adjust syntax for Python 3
compatibility.
Include "sys.abiflags" string as part of python library name, if
that attribute exists (Python 3).
* python/python-internal.h (IS_PY3): Define if Python 3.
(Py_TPFLAGS_HAVE_ITER, Py_TPFLAGS_CHECKTYPES): Define with
placeholder value if Python 3.
(PyInt_Check, PyInt_FromLong, PyInt_AsLong, PyString_FromString,
PyString_Decode, PyString_FromFormat, PyString_Check): Define as
analogous Python 3 API function if Python 3.
(PyVarObject_HEAD_INIT): Define if Python 2.4.
* python/python.c (eval_python_command): Omit Py_FlushLine call if
Python 3.
(_initialize_python): Convert argc to wchar_t** if Python 3.
Add module initialization for Python 3.
(finish_python_initialization): Pass wchar_t * argument to
PySys_SetPath if Python 3.
* python/lib/gdb/__init__.py: Define "reload" if Python 3.
(_GdbFile): New class for common output file behavior.
(GdbOutFile): Subclass from _GdbFile.
(GdbOutputErrorFile): Ditto.
(auto_load_packages): Adjust syntax for Python 3 compatibility.
* python/lib/gdb/printing.py: Define basestr and int if Python 3.
* python/lib/gdb/prompt.py: Use sorted() function rather than
sort() method.
* python/lib/gdb/command/explore.py: Define raw_input if Python 3.
Adjust syntax for Python 3 compatibility.
* python/lib/gdb/command/pretty_printers.py: Use sorted() function
rather than sort() method.
Adjust syntax for Python 3 compatibility.
* doc/gdb.texinfo (Inferior.read_memory): Mention that the return
value is a memoryview object if Python 3.
Index: gdb/varobj.c
===================================================================
RCS file: /cvs/src/src/gdb/varobj.c,v
retrieving revision 1.200
diff -u -r1.200 varobj.c
--- gdb/varobj.c 6 Aug 2012 18:44:44 -0000 1.200
+++ gdb/varobj.c 12 Nov 2012 15:51:27 -0000
@@ -2910,12 +2910,10 @@
string_print. Otherwise just return the extracted
string as a value. */
- PyObject *py_str
- = python_string_to_target_python_string (output);
+ char *s = python_string_to_target_string (output);
- if (py_str)
+ if (s)
{
- char *s = PyString_AsString (py_str);
char *hint;
hint = gdbpy_get_display_hint (value_formatter);
@@ -2926,10 +2924,10 @@
xfree (hint);
}
- len = PyString_Size (py_str);
+ len = strlen (s);
thevalue = xmemdup (s, len + 1, len + 1);
type = builtin_type (gdbarch)->builtin_char;
- Py_DECREF (py_str);
+ xfree (s);
if (!string_print)
{
Index: gdb/doc/gdb.texinfo
===================================================================
RCS file: /cvs/src/src/gdb/doc/gdb.texinfo,v
retrieving revision 1.1017
diff -u -r1.1017 gdb.texinfo
--- gdb/doc/gdb.texinfo 5 Nov 2012 19:36:38 -0000 1.1017
+++ gdb/doc/gdb.texinfo 12 Nov 2012 15:51:30 -0000
@@ -23982,7 +23982,8 @@
Read @var{length} bytes of memory from the inferior, starting at
@var{address}. Returns a buffer object, which behaves much like an array
or a string. It can be modified and given to the
-@code{Inferior.write_memory} function.
+@code{Inferior.write_memory} function. In @code{Python} 3, the return
+value is a @code{memoryview} object.
@end defun
@findex Inferior.write_memory
Index: gdb/python/py-block.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-block.c,v
retrieving revision 1.12
diff -u -r1.12 py-block.c
--- gdb/python/py-block.c 10 May 2012 19:50:09 -0000 1.12
+++ gdb/python/py-block.c 12 Nov 2012 15:51:30 -0000
@@ -475,8 +475,7 @@
};
PyTypeObject block_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Block", /*tp_name*/
sizeof (block_object), /*tp_basicsize*/
0, /*tp_itemsize*/
@@ -516,8 +515,7 @@
};
static PyTypeObject block_syms_iterator_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.BlockIterator", /*tp_name*/
sizeof (block_syms_iterator_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-breakpoint.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-breakpoint.c,v
retrieving revision 1.34
diff -u -r1.34 py-breakpoint.c
--- gdb/python/py-breakpoint.c 14 May 2012 15:38:40 -0000 1.34
+++ gdb/python/py-breakpoint.c 12 Nov 2012 15:51:30 -0000
@@ -981,8 +981,7 @@
PyTypeObject breakpoint_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Breakpoint", /*tp_name*/
sizeof (breakpoint_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-cmd.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-cmd.c,v
retrieving revision 1.21
diff -u -r1.21 py-cmd.c
--- gdb/python/py-cmd.c 13 Jun 2012 15:47:16 -0000 1.21
+++ gdb/python/py-cmd.c 12 Nov 2012 15:51:30 -0000
@@ -607,8 +607,7 @@
static PyTypeObject cmdpy_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Command", /*tp_name*/
sizeof (cmdpy_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-event.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-event.c,v
retrieving revision 1.4
diff -u -r1.4 py-event.c
--- gdb/python/py-event.c 15 Aug 2012 14:22:02 -0000 1.4
+++ gdb/python/py-event.c 12 Nov 2012 15:51:30 -0000
@@ -142,8 +142,7 @@
PyTypeObject event_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Event", /* tp_name */
sizeof (event_object), /* tp_basicsize */
0, /* tp_itemsize */
Index: gdb/python/py-event.h
===================================================================
RCS file: /cvs/src/src/gdb/python/py-event.h,v
retrieving revision 1.5
diff -u -r1.5 py-event.h
--- gdb/python/py-event.h 4 Jan 2012 08:17:25 -0000 1.5
+++ gdb/python/py-event.h 12 Nov 2012 15:51:30 -0000
@@ -49,8 +49,7 @@
\
qual PyTypeObject name##_event_object_type = \
{ \
- PyObject_HEAD_INIT (NULL) \
- 0, /* ob_size */ \
+ PyVarObject_HEAD_INIT (NULL, 0) \
py_path, /* tp_name */ \
sizeof (event_object), /* tp_basicsize */ \
0, /* tp_itemsize */ \
Index: gdb/python/py-evtregistry.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-evtregistry.c,v
retrieving revision 1.3
diff -u -r1.3 py-evtregistry.c
--- gdb/python/py-evtregistry.c 4 Jan 2012 08:17:25 -0000 1.3
+++ gdb/python/py-evtregistry.c 12 Nov 2012 15:51:30 -0000
@@ -131,8 +131,7 @@
static PyTypeObject eventregistry_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.EventRegistry", /* tp_name */
sizeof (eventregistry_object), /* tp_basicsize */
0, /* tp_itemsize */
Index: gdb/python/py-evts.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-evts.c,v
retrieving revision 1.4
diff -u -r1.4 py-evts.c
--- gdb/python/py-evts.c 4 Jan 2012 08:17:25 -0000 1.4
+++ gdb/python/py-evts.c 12 Nov 2012 15:51:30 -0000
@@ -19,6 +19,21 @@
#include "py-events.h"
+#ifdef IS_PY3K
+static struct PyModuleDef EventModuleDef =
+{
+ PyModuleDef_HEAD_INIT,
+ "gdb.events",
+ NULL,
+ -1,
+ NULL,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+#endif
+
/* Initialize python events. */
static int
@@ -44,7 +59,11 @@
void
gdbpy_initialize_py_events (void)
{
+#ifdef IS_PY3K
+ gdb_py_events.module = PyModule_Create (&EventModuleDef);
+#else
gdb_py_events.module = Py_InitModule ("events", NULL);
+#endif
if (!gdb_py_events.module)
goto fail;
@@ -61,7 +80,9 @@
if (add_new_registry (&gdb_py_events.new_objfile, "new_objfile") < 0)
goto fail;
+#ifndef IS_PY3K
Py_INCREF (gdb_py_events.module);
+#endif
if (PyModule_AddObject (gdb_module,
"events",
(PyObject *) gdb_py_events.module) < 0)
Index: gdb/python/py-finishbreakpoint.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-finishbreakpoint.c,v
retrieving revision 1.7
diff -u -r1.7 py-finishbreakpoint.c
--- gdb/python/py-finishbreakpoint.c 18 May 2012 21:02:52 -0000 1.7
+++ gdb/python/py-finishbreakpoint.c 12 Nov 2012 15:51:30 -0000
@@ -425,8 +425,7 @@
static PyTypeObject finish_breakpoint_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.FinishBreakpoint", /*tp_name*/
sizeof (struct finish_breakpoint_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-frame.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-frame.c,v
retrieving revision 1.26
diff -u -r1.26 py-frame.c
--- gdb/python/py-frame.c 7 Feb 2012 19:47:15 -0000 1.26
+++ gdb/python/py-frame.c 12 Nov 2012 15:51:30 -0000
@@ -662,8 +662,7 @@
};
PyTypeObject frame_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Frame", /* tp_name */
sizeof (frame_object), /* tp_basicsize */
0, /* tp_itemsize */
Index: gdb/python/py-function.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-function.c,v
retrieving revision 1.12
diff -u -r1.12 py-function.c
--- gdb/python/py-function.c 4 Jan 2012 08:17:25 -0000 1.12
+++ gdb/python/py-function.c 12 Nov 2012 15:51:30 -0000
@@ -208,8 +208,7 @@
static PyTypeObject fnpy_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Function", /*tp_name*/
sizeof (PyObject), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-inferior.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-inferior.c,v
retrieving revision 1.25
diff -u -r1.25 py-inferior.c
--- gdb/python/py-inferior.c 22 Aug 2012 15:17:21 -0000 1.25
+++ gdb/python/py-inferior.c 12 Nov 2012 15:51:30 -0000
@@ -454,9 +454,14 @@
membuf_obj->addr = addr;
membuf_obj->length = length;
+#ifdef IS_PY3K
+ result = PyMemoryView_FromObject ((PyObject *) membuf_obj);
+#else
result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0,
Py_END_OF_BUFFER);
+#endif
Py_DECREF (membuf_obj);
+
return result;
}
@@ -476,12 +481,22 @@
PyObject *addr_obj, *length_obj = NULL;
volatile struct gdb_exception except;
static char *keywords[] = { "address", "buffer", "length", NULL };
+#ifdef IS_PY3K
+ Py_buffer pybuf;
+ if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords,
+ &addr_obj, &pybuf,
+ &length_obj))
+ return NULL;
+ buffer = pybuf.buf;
+ buf_len = pybuf.len;
+#else
if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords,
&addr_obj, &buffer, &buf_len,
&length_obj))
return NULL;
+#endif
TRY_CATCH (except, RETURN_MASK_ALL)
{
@@ -528,6 +543,23 @@
pulongest (membuf_obj->length));
}
+#ifdef IS_PY3K
+static int
+get_buffer (PyObject *self, Py_buffer *buf, int flags)
+{
+ membuf_object *membuf_obj = (membuf_object *) self;
+ int ret;
+
+ ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer,
+ membuf_obj->length, 0,
+ PyBUF_CONTIG);
+ buf->format = "c";
+
+ return ret;
+}
+
+#else
+
static Py_ssize_t
get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr)
{
@@ -572,6 +604,8 @@
return ret;
}
+#endif /* IS_PY3K */
+
/* Implementation of
gdb.search_memory (address, length, pattern). ADDRESS is the
address to start the search. LENGTH specifies the scope of the
@@ -585,17 +619,41 @@
{
CORE_ADDR start_addr, length;
static char *keywords[] = { "address", "length", "pattern", NULL };
- PyObject *pattern, *start_addr_obj, *length_obj;
+ PyObject *start_addr_obj, *length_obj;
volatile struct gdb_exception except;
Py_ssize_t pattern_size;
const void *buffer;
CORE_ADDR found_addr;
int found = 0;
+#ifdef IS_PY3K
+ Py_buffer pybuf;
- if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
+ if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords,
&start_addr_obj, &length_obj,
+ &pybuf))
+ return NULL;
+
+ buffer = pybuf.buf;
+ pattern_size = pybuf.len;
+#else
+ PyObject *pattern;
+
+ if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords,
+ &start_addr_obj, &length_obj,
&pattern))
+ return NULL;
+
+ if (!PyObject_CheckReadBuffer (pattern))
+ {
+ PyErr_SetString (PyExc_RuntimeError,
+ _("The pattern is not a Python buffer."));
+
+ return NULL;
+ }
+
+ if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1)
return NULL;
+#endif
if (get_addr_from_python (start_addr_obj, &start_addr)
&& get_addr_from_python (length_obj, &length))
@@ -619,17 +677,6 @@
else
return NULL;
- if (!PyObject_CheckReadBuffer (pattern))
- {
- PyErr_SetString (PyExc_RuntimeError,
- _("The pattern is not a Python buffer."));
-
- return NULL;
- }
-
- if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1)
- return NULL;
-
TRY_CATCH (except, RETURN_MASK_ALL)
{
found = target_search_memory (start_addr, length,
@@ -777,8 +824,7 @@
static PyTypeObject inferior_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /* ob_size */
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Inferior", /* tp_name */
sizeof (inferior_object), /* tp_basicsize */
0, /* tp_itemsize */
@@ -817,6 +863,13 @@
0 /* tp_alloc */
};
+#ifdef IS_PY3K
+static PyBufferProcs buffer_procs = {
+ get_buffer
+};
+
+#else
+
/* Python doesn't provide a decent way to get compatibility here. */
#if HAVE_LIBPYTHON2_4
#define CHARBUFFERPROC_NAME getcharbufferproc
@@ -832,10 +885,10 @@
Python 2.5. */
(CHARBUFFERPROC_NAME) get_char_buffer
};
+#endif /* IS_PY3K */
static PyTypeObject membuf_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Membuf", /*tp_name*/
sizeof (membuf_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-infthread.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-infthread.c,v
retrieving revision 1.7
diff -u -r1.7 py-infthread.c
--- gdb/python/py-infthread.c 18 May 2012 21:02:52 -0000 1.7
+++ gdb/python/py-infthread.c 12 Nov 2012 15:51:30 -0000
@@ -301,8 +301,7 @@
static PyTypeObject thread_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.InferiorThread", /*tp_name*/
sizeof (thread_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-lazy-string.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-lazy-string.c,v
retrieving revision 1.12
diff -u -r1.12 py-lazy-string.c
--- gdb/python/py-lazy-string.c 1 Mar 2012 21:06:54 -0000 1.12
+++ gdb/python/py-lazy-string.c 12 Nov 2012 15:51:30 -0000
@@ -216,8 +216,7 @@
};
static PyTypeObject lazy_string_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.LazyString", /*tp_name*/
sizeof (lazy_string_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-objfile.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-objfile.c,v
retrieving revision 1.11
diff -u -r1.11 py-objfile.c
--- gdb/python/py-objfile.c 4 Jan 2012 08:17:25 -0000 1.11
+++ gdb/python/py-objfile.c 12 Nov 2012 15:51:30 -0000
@@ -58,7 +58,7 @@
objfile_object *self = (objfile_object *) o;
Py_XDECREF (self->printers);
- self->ob_type->tp_free ((PyObject *) self);
+ o->ob_type->tp_free ((PyObject *) self);
}
static PyObject *
@@ -215,8 +215,7 @@
static PyTypeObject objfile_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Objfile", /*tp_name*/
sizeof (objfile_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-param.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-param.c,v
retrieving revision 1.15
diff -u -r1.15 py-param.c
--- gdb/python/py-param.c 4 Jan 2012 08:17:25 -0000 1.15
+++ gdb/python/py-param.c 12 Nov 2012 15:51:30 -0000
@@ -102,7 +102,11 @@
get_attr (PyObject *obj, PyObject *attr_name)
{
if (PyString_Check (attr_name)
+#ifdef IS_PY3K
+ && ! PyUnicode_CompareWithASCIIString (attr_name, "value"))
+#else
&& ! strcmp (PyString_AsString (attr_name), "value"))
+#endif
{
parmpy_object *self = (parmpy_object *) obj;
@@ -276,7 +280,11 @@
set_attr (PyObject *obj, PyObject *attr_name, PyObject *val)
{
if (PyString_Check (attr_name)
+#ifdef IS_PY3K
+ && ! PyUnicode_CompareWithASCIIString (attr_name, "value"))
+#else
&& ! strcmp (PyString_AsString (attr_name), "value"))
+#endif
{
if (!val)
{
@@ -773,8 +781,7 @@
static PyTypeObject parmpy_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Parameter", /*tp_name*/
sizeof (parmpy_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-prettyprint.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-prettyprint.c,v
retrieving revision 1.28
diff -u -r1.28 py-prettyprint.c
--- gdb/python/py-prettyprint.c 13 Sep 2012 21:49:31 -0000 1.28
+++ gdb/python/py-prettyprint.c 12 Nov 2012 15:51:30 -0000
@@ -348,8 +348,13 @@
struct type *type;
make_cleanup_py_decref (string);
+#ifdef IS_PY3K
+ output = (gdb_byte *) PyBytes_AS_STRING (string);
+ length = PyBytes_GET_SIZE (string);
+#else
output = PyString_AsString (string);
length = PyString_Size (string);
+#endif
type = builtin_type (gdbarch)->builtin_char;
if (hint && !strcmp (hint, "string"))
@@ -383,6 +388,7 @@
return result;
}
+#ifndef IS_PY3K
static void
py_restore_tstate (void *p)
{
@@ -458,6 +464,7 @@
make_cleanup (py_restore_tstate, frame->f_back);
return (PyObject *) frame;
}
+#endif
/* Helper for apply_val_pretty_printer that formats children of the
printer, if any exist. If is_py_none is true, then nothing has
@@ -471,7 +478,10 @@
{
int is_map, is_array, done_flag, pretty;
unsigned int i;
- PyObject *children, *iter, *frame;
+ PyObject *children, *iter;
+#ifndef IS_PY3K
+ PyObject *frame;
+#endif
struct cleanup *cleanups;
if (! PyObject_HasAttr (printer, gdbpy_children_cst))
@@ -515,6 +525,7 @@
/* Manufacture a dummy Python frame to work around Python 2.4 bug,
where it insists on having a non-NULL tstate->frame when
a generator is called. */
+#ifndef IS_PY3K
frame = push_dummy_python_frame ();
if (!frame)
{
@@ -522,6 +533,7 @@
goto done;
}
make_cleanup_py_decref (frame);
+#endif
done_flag = 0;
for (i = 0; i < options->print_max; ++i)
Index: gdb/python/py-progspace.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-progspace.c,v
retrieving revision 1.9
diff -u -r1.9 py-progspace.c
--- gdb/python/py-progspace.c 22 Aug 2012 15:17:21 -0000 1.9
+++ gdb/python/py-progspace.c 12 Nov 2012 15:51:30 -0000
@@ -202,8 +202,7 @@
static PyTypeObject pspace_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Progspace", /*tp_name*/
sizeof (pspace_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-symbol.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-symbol.c,v
retrieving revision 1.15
diff -u -r1.15 py-symbol.c
--- gdb/python/py-symbol.c 15 Oct 2012 15:20:26 -0000 1.15
+++ gdb/python/py-symbol.c 12 Nov 2012 15:51:30 -0000
@@ -561,8 +561,7 @@
};
PyTypeObject symbol_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Symbol", /*tp_name*/
sizeof (symbol_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-symtab.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-symtab.c,v
retrieving revision 1.12
diff -u -r1.12 py-symtab.c
--- gdb/python/py-symtab.c 18 Oct 2012 20:14:45 -0000 1.12
+++ gdb/python/py-symtab.c 12 Nov 2012 15:51:30 -0000
@@ -307,7 +307,7 @@
Py_DECREF (self_sal->symtab);
xfree (self_sal->sal);
- self_sal->ob_type->tp_free (self);
+ self->ob_type->tp_free (self);
}
/* Given a sal, and a sal_object that has previously been allocated
@@ -539,8 +539,7 @@
};
static PyTypeObject symtab_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Symtab", /*tp_name*/
sizeof (symtab_object), /*tp_basicsize*/
0, /*tp_itemsize*/
@@ -590,8 +589,7 @@
};
static PyTypeObject sal_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Symtab_and_line", /*tp_name*/
sizeof (sal_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-type.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-type.c,v
retrieving revision 1.43
diff -u -r1.43 py-type.c
--- gdb/python/py-type.c 16 Aug 2012 07:36:28 -0000 1.43
+++ gdb/python/py-type.c 12 Nov 2012 15:51:30 -0000
@@ -122,7 +122,7 @@
field_object *f = (field_object *) obj;
Py_XDECREF (f->dict);
- f->ob_type->tp_free (obj);
+ obj->ob_type->tp_free (obj);
}
static PyObject *
@@ -1260,7 +1260,7 @@
if (type->next)
type->next->prev = type->prev;
- type->ob_type->tp_free (type);
+ obj->ob_type->tp_free (type);
}
/* Return number of fields ("length" of the field dictionary). */
@@ -1655,7 +1655,9 @@
NULL, /* nb_add */
NULL, /* nb_subtract */
NULL, /* nb_multiply */
+#ifndef IS_PY3K
NULL, /* nb_divide */
+#endif
NULL, /* nb_remainder */
NULL, /* nb_divmod */
NULL, /* nb_power */
@@ -1669,12 +1671,19 @@
NULL, /* nb_and */
NULL, /* nb_xor */
NULL, /* nb_or */
+#ifdef IS_PY3K
+ NULL, /* nb_int */
+ NULL, /* reserved */
+#else
NULL, /* nb_coerce */
NULL, /* nb_int */
NULL, /* nb_long */
+#endif
NULL, /* nb_float */
+#ifndef IS_PY3K
NULL, /* nb_oct */
NULL /* nb_hex */
+#endif
};
static PyMappingMethods typy_mapping = {
@@ -1685,8 +1694,7 @@
static PyTypeObject type_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Type", /*tp_name*/
sizeof (type_object), /*tp_basicsize*/
0, /*tp_itemsize*/
@@ -1735,8 +1743,7 @@
static PyTypeObject field_object_type =
{
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Field", /*tp_name*/
sizeof (field_object), /*tp_basicsize*/
0, /*tp_itemsize*/
@@ -1777,8 +1784,7 @@
};
static PyTypeObject type_iterator_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.TypeIterator", /*tp_name*/
sizeof (typy_iterator_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/py-utils.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-utils.c,v
retrieving revision 1.13
diff -u -r1.13 py-utils.c
--- gdb/python/py-utils.c 1 Mar 2012 21:06:54 -0000 1.13
+++ gdb/python/py-utils.c 12 Nov 2012 15:51:30 -0000
@@ -54,7 +54,8 @@
As an added bonus, the functions accepts a unicode string and returns it
right away, so callers don't need to check which kind of string they've
- got.
+ got. In Python 3, all strings are Unicode so this case is always the
+ one that applies.
If the given object is not one of the mentioned string types, NULL is
returned, with the TypeError python exception set. */
@@ -70,9 +71,10 @@
unicode_str = obj;
Py_INCREF (obj);
}
-
+#ifndef IS_PY3K
else if (PyString_Check (obj))
unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL);
+#endif
else
{
PyErr_SetString (PyExc_TypeError,
@@ -99,7 +101,11 @@
if (string == NULL)
return NULL;
+#ifdef IS_PY3K
+ result = xstrdup (PyBytes_AsString (string));
+#else
result = xstrdup (PyString_AsString (string));
+#endif
Py_DECREF (string);
@@ -113,14 +119,8 @@
static PyObject *
unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset)
{
- PyObject *string;
-
/* Translate string to named charset. */
- string = PyUnicode_AsEncodedString (unicode_str, charset, NULL);
- if (string == NULL)
- return NULL;
-
- return string;
+ return PyUnicode_AsEncodedString (unicode_str, charset, NULL);
}
/* Returns a newly allocated string with the contents of the given unicode
@@ -167,7 +167,9 @@
/* Converts a python string (8-bit or unicode) to a target string in the
target's charset. Returns NULL on error, with a python exception
- set. */
+ set.
+
+ In Python 3, the returned object is a "bytes" object (not a string). */
PyObject *
python_string_to_target_python_string (PyObject *obj)
{
@@ -221,7 +223,11 @@
int
gdbpy_is_string (PyObject *obj)
{
+#ifdef IS_PY3K
+ return PyUnicode_Check (obj);
+#else
return PyString_Check (obj) || PyUnicode_Check (obj);
+#endif
}
/* Return the string representation of OBJ, i.e., str (obj).
@@ -235,7 +241,11 @@
if (str_obj != NULL)
{
+#ifdef IS_PY3K
+ char *msg = python_string_to_host_string (str_obj);
+#else
char *msg = xstrdup (PyString_AsString (str_obj));
+#endif
Py_DECREF (str_obj);
return msg;
@@ -335,6 +345,11 @@
PyObject *
gdb_py_object_from_longest (LONGEST l)
{
+#ifdef IS_PY3K
+ if (sizeof (l) > sizeof (long))
+ return PyLong_FromLongLong (l);
+ return PyLong_FromLong (l);
+#else
#ifdef HAVE_LONG_LONG /* Defined by Python. */
/* If we have 'long long', and the value overflows a 'long', use a
Python Long; otherwise use a Python Int. */
@@ -343,6 +358,7 @@
return PyLong_FromLongLong (l);
#endif
return PyInt_FromLong (l);
+#endif
}
/* Convert a ULONGEST to the appropriate Python object -- either an
@@ -351,6 +367,11 @@
PyObject *
gdb_py_object_from_ulongest (ULONGEST l)
{
+#ifdef IS_PY3K
+ if (sizeof (l) > sizeof (unsigned long))
+ return PyLong_FromUnsignedLongLong (l);
+ return PyLong_FromUnsignedLong (l);
+#else
#ifdef HAVE_LONG_LONG /* Defined by Python. */
/* If we have 'long long', and the value overflows a 'long', use a
Python Long; otherwise use a Python Int. */
@@ -362,6 +383,7 @@
return PyLong_FromUnsignedLong (l);
return PyInt_FromLong (l);
+#endif
}
/* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts
Index: gdb/python/py-value.c
===================================================================
RCS file: /cvs/src/src/gdb/python/py-value.c,v
retrieving revision 1.36
diff -u -r1.36 py-value.c
--- gdb/python/py-value.c 30 Mar 2012 20:05:55 -0000 1.36
+++ gdb/python/py-value.c 12 Nov 2012 15:51:30 -0000
@@ -106,7 +106,7 @@
Py_XDECREF (self->dynamic_type);
- self->ob_type->tp_free (self);
+ obj->ob_type->tp_free (self);
}
/* Helper to push a Value object on the global list. */
@@ -1140,6 +1140,7 @@
|| (ptr_ok && TYPE_CODE (type) == TYPE_CODE_PTR));
}
+#ifndef IS_PY3K
/* Implements conversion to int. */
static PyObject *
valpy_int (PyObject *self)
@@ -1161,6 +1162,7 @@
return gdb_py_object_from_longest (l);
}
+#endif
/* Implements conversion to long. */
static PyObject *
@@ -1335,9 +1337,14 @@
value = value_copy (((value_object *) result)->value);
}
else
+#ifdef IS_PY3K
+ PyErr_Format (PyExc_TypeError,
+ _("Could not convert Python object: %S."), obj);
+#else
PyErr_Format (PyExc_TypeError,
_("Could not convert Python object: %s."),
PyString_AsString (PyObject_Str (obj)));
+#endif
}
if (except.reason < 0)
{
@@ -1439,7 +1446,9 @@
valpy_add,
valpy_subtract,
valpy_multiply,
+#ifndef IS_PY3K
valpy_divide,
+#endif
valpy_remainder,
NULL, /* nb_divmod */
valpy_power, /* nb_power */
@@ -1453,12 +1462,31 @@
valpy_and, /* nb_and */
valpy_xor, /* nb_xor */
valpy_or, /* nb_or */
+#ifdef IS_PY3K
+ valpy_long, /* nb_int */
+ NULL, /* reserved */
+#else
NULL, /* nb_coerce */
valpy_int, /* nb_int */
valpy_long, /* nb_long */
+#endif
valpy_float, /* nb_float */
+#ifndef IS_PY3K
NULL, /* nb_oct */
- NULL /* nb_hex */
+ NULL, /* nb_hex */
+#endif
+ NULL, /* nb_inplace_add */
+ NULL, /* nb_inplace_subtract */
+ NULL, /* nb_inplace_multiply */
+ NULL, /* nb_inplace_remainder */
+ NULL, /* nb_inplace_power */
+ NULL, /* nb_inplace_lshift */
+ NULL, /* nb_inplace_rshift */
+ NULL, /* nb_inplace_and */
+ NULL, /* nb_inplace_xor */
+ NULL, /* nb_inplace_or */
+ NULL, /* nb_floor_divide */
+ valpy_divide /* nb_true_divide */
};
static PyMappingMethods value_object_as_mapping = {
@@ -1468,8 +1496,7 @@
};
PyTypeObject value_object_type = {
- PyObject_HEAD_INIT (NULL)
- 0, /*ob_size*/
+ PyVarObject_HEAD_INIT (NULL, 0)
"gdb.Value", /*tp_name*/
sizeof (value_object), /*tp_basicsize*/
0, /*tp_itemsize*/
Index: gdb/python/python-config.py
===================================================================
RCS file: /cvs/src/src/gdb/python/python-config.py,v
retrieving revision 1.3
diff -u -r1.3 python-config.py
--- gdb/python/python-config.py 31 Jan 2011 04:42:08 -0000 1.3
+++ gdb/python/python-config.py 12 Nov 2012 15:51:30 -0000
@@ -10,8 +10,8 @@
'ldflags', 'help']
def exit_with_usage(code=1):
- print >>sys.stderr, "Usage: %s [%s]" % (sys.argv[0],
- '|'.join('--'+opt for opt in valid_opts))
+ sys.stderr.write ("Usage: %s [%s]\n" % (sys.argv[0],
+ '|'.join('--'+opt for opt in valid_opts)))
sys.exit(code)
try:
@@ -24,6 +24,7 @@
pyver = sysconfig.get_config_var('VERSION')
getvar = sysconfig.get_config_var
+abiflags = getattr (sys, "abiflags", "")
opt_flags = [flag for (flag, val) in opts]
@@ -44,17 +45,17 @@
for opt in opt_flags:
if opt == '--prefix':
- print to_unix_path(sysconfig.PREFIX)
+ print (to_unix_path(sysconfig.PREFIX))
elif opt == '--exec-prefix':
- print to_unix_path(sysconfig.EXEC_PREFIX)
+ print (to_unix_path(sysconfig.EXEC_PREFIX))
elif opt in ('--includes', '--cflags'):
flags = ['-I' + sysconfig.get_python_inc(),
'-I' + sysconfig.get_python_inc(plat_specific=True)]
if opt == '--cflags':
flags.extend(getvar('CFLAGS').split())
- print to_unix_path(' '.join(flags))
+ print (to_unix_path(' '.join(flags)))
elif opt in ('--libs', '--ldflags'):
libs = []
@@ -62,7 +63,7 @@
libs.extend(getvar('LIBS').split())
if getvar('SYSLIBS') is not None:
libs.extend(getvar('SYSLIBS').split())
- libs.append('-lpython'+pyver)
+ libs.append('-lpython'+pyver + abiflags)
# add the prefix/lib/pythonX.Y/config dir, but only if there is no
# shared library in prefix/lib/.
if opt == '--ldflags':
@@ -73,5 +74,5 @@
libs.insert(0, '-L' + sysconfig.PREFIX + '/libs')
if getvar('LINKFORSHARED') is not None:
libs.extend(getvar('LINKFORSHARED').split())
- print to_unix_path(' '.join(libs))
+ print (to_unix_path(' '.join(libs)))
Index: gdb/python/python-internal.h
===================================================================
RCS file: /cvs/src/src/gdb/python/python-internal.h,v
retrieving revision 1.59
diff -u -r1.59 python-internal.h
--- gdb/python/python-internal.h 13 Sep 2012 21:49:31 -0000 1.59
+++ gdb/python/python-internal.h 12 Nov 2012 15:51:30 -0000
@@ -49,12 +49,36 @@
from including our python/python.h header file. */
#include <Python.h>
#include <frameobject.h>
+
+#if PY_MAJOR_VERSION >= 3
+#define IS_PY3K 1
+#endif
+
+#ifdef IS_PY3K
+#define Py_TPFLAGS_HAVE_ITER 0
+#define Py_TPFLAGS_CHECKTYPES 0
+
+#define PyInt_Check PyLong_Check
+#define PyInt_FromLong PyLong_FromLong
+#define PyInt_AsLong PyLong_AsLong
+
+#define PyString_FromString PyUnicode_FromString
+#define PyString_Decode PyUnicode_Decode
+#define PyString_FromFormat PyUnicode_FromFormat
+#define PyString_Check PyUnicode_Check
+#endif
+
#if HAVE_LIBPYTHON2_4
/* Py_ssize_t is not defined until 2.5.
Logical type for Py_ssize_t is Py_intptr_t, but that fails in 64-bit
compilation due to several apparent mistakes in python2.4 API, so we
use 'int' instead. */
typedef int Py_ssize_t;
+
+/* Python 2.4 does not define PyVarObject_HEAD_INIT. */
+#define PyVarObject_HEAD_INIT(type, size) \
+ PyObject_HEAD_INIT(type) size,
+
#endif
/* If Python.h does not define WITH_THREAD, then the various
Index: gdb/python/python.c
===================================================================
RCS file: /cvs/src/src/gdb/python/python.c,v
retrieving revision 1.98
diff -u -r1.98 python.c
--- gdb/python/python.c 21 Sep 2012 12:57:34 -0000 1.98
+++ gdb/python/python.c 12 Nov 2012 15:51:30 -0000
@@ -70,9 +70,14 @@
#include "gdbthread.h"
#include "observer.h"
#include "interps.h"
+#include "event-top.h"
static PyMethodDef GdbMethods[];
+#ifdef IS_PY3K
+static struct PyModuleDef GdbModuleDef;
+#endif
+
PyObject *gdb_module;
PyObject *gdb_python_module;
@@ -198,8 +203,10 @@
return -1;
Py_DECREF (v);
+#ifndef IS_PY3K
if (Py_FlushLine ())
PyErr_Clear ();
+#endif
return 0;
}
@@ -1295,6 +1302,14 @@
{
char *cmd_name;
struct cmd_list_element *cmd;
+ char *progname;
+#ifdef IS_PY3K
+ int i;
+ size_t progsize, count;
+ char *oldloc;
+ wchar_t *progname_copy;
+#endif
+
add_com ("python-interactive", class_obscure,
python_interactive_command,
@@ -1374,14 +1389,44 @@
/foo/bin/python
/foo/lib/pythonX.Y/...
This must be done before calling Py_Initialize. */
- Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin",
- SLASH_STRING, "python", NULL));
+ progname = concat (ldirname (python_libdir), SLASH_STRING, "bin",
+ SLASH_STRING, "python", NULL);
+#ifdef IS_PY3K
+ oldloc = setlocale (LC_ALL, NULL);
+ setlocale (LC_ALL, "");
+ progsize = strlen (progname);
+ if (progsize == (size_t) -1)
+ {
+ fprintf(stderr, "Could not convert python path to string\n");
+ exit (1);
+ }
+ progname_copy = PyMem_Malloc((progsize + 1) * sizeof (wchar_t));
+ if (!progname_copy)
+ {
+ fprintf(stderr, "out of memory\n");
+ exit (1);
+ }
+ count = mbstowcs (progname_copy, progname, progsize + 1);
+ if (count == (size_t) -1) {
+ fprintf(stderr, "Could not convert python path to string\n");
+ exit (1);
+ }
+ setlocale (LC_ALL, oldloc);
+ Py_SetProgramName (progname_copy);
+#else
+ Py_SetProgramName (progname);
+#endif
#endif
Py_Initialize ();
PyEval_InitThreads ();
+#ifdef IS_PY3K
+ gdb_module = PyModule_Create (&GdbModuleDef);
+ _PyImport_FixupBuiltin (gdb_module, "_gdb");
+#else
gdb_module = Py_InitModule ("_gdb", GdbMethods);
+#endif
/* The casts to (char*) are for python 2.4. */
PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version);
@@ -1476,7 +1521,17 @@
sys_path = PySys_GetObject ("path");
- if (sys_path && PyList_Check (sys_path))
+ /* If sys.path is not defined yet, define it first. */
+ if (!(sys_path && PyList_Check (sys_path)))
+ {
+#ifdef IS_PY3K
+ PySys_SetPath (L"");
+#else
+ PySys_SetPath ("");
+#endif
+ sys_path = PySys_GetObject ("path");
+ }
+ if (sys_path && PyList_Check (sys_path))
{
PyObject *pythondir;
int err;
@@ -1492,7 +1547,7 @@
Py_DECREF (pythondir);
}
else
- PySys_SetPath (gdb_pythondir);
+ goto fail;
/* Import the gdb module to finish the initialization, and
add it to __main__ for convenience. */
@@ -1632,4 +1687,18 @@
{NULL, NULL, 0, NULL}
};
+#ifdef IS_PY3K
+static struct PyModuleDef GdbModuleDef =
+{
+ PyModuleDef_HEAD_INIT,
+ "_gdb",
+ NULL,
+ -1,
+ GdbMethods,
+ NULL,
+ NULL,
+ NULL,
+ NULL
+};
+#endif
#endif /* HAVE_PYTHON */
Index: gdb/python/lib/gdb/__init__.py
===================================================================
RCS file: /cvs/src/src/gdb/python/lib/gdb/__init__.py,v
retrieving revision 1.6
diff -u -r1.6 __init__.py
--- gdb/python/lib/gdb/__init__.py 13 Sep 2012 21:49:31 -0000 1.6
+++ gdb/python/lib/gdb/__init__.py 12 Nov 2012 15:51:30 -0000
@@ -18,9 +18,17 @@
import sys
import _gdb
+if sys.version_info[0] > 2:
+ # Python 3 moved "reload"
+ from imp import reload
+
from _gdb import *
-class GdbOutputFile:
+class _GdbFile (object):
+ # These two are needed in Python 3
+ encoding = "UTF-8"
+ errors = "strict"
+
def close(self):
# Do nothing.
return None
@@ -28,9 +36,6 @@
def isatty(self):
return False
- def write(self, s):
- write(s, stream=STDOUT)
-
def writelines(self, iterable):
for line in iterable:
self.write(line)
@@ -38,26 +43,16 @@
def flush(self):
flush()
-sys.stdout = GdbOutputFile()
-
-class GdbOutputErrorFile:
- def close(self):
- # Do nothing.
- return None
+class GdbOutputFile (_GdbFile):
+ def write(self, s):
+ write(s, stream=STDOUT)
- def isatty(self):
- return False
+sys.stdout = GdbOutputFile()
+class GdbOutputErrorFile (_GdbFile):
def write(self, s):
write(s, stream=STDERR)
- def writelines(self, iterable):
- for line in iterable:
- self.write(line)
-
- def flush(self):
- flush()
-
sys.stderr = GdbOutputErrorFile()
# Default prompt hook does nothing.
@@ -104,7 +99,7 @@
else:
__import__(modname)
except:
- print >> sys.stderr, traceback.format_exc()
+ sys.stderr.write (traceback.format_exc() + "\n")
auto_load_packages()
Index: gdb/python/lib/gdb/printing.py
===================================================================
RCS file: /cvs/src/src/gdb/python/lib/gdb/printing.py,v
retrieving revision 1.9
diff -u -r1.9 printing.py
--- gdb/python/lib/gdb/printing.py 18 Apr 2012 06:46:46 -0000 1.9
+++ gdb/python/lib/gdb/printing.py 12 Nov 2012 15:51:30 -0000
@@ -19,7 +19,12 @@
import gdb
import gdb.types
import re
+import sys
+if sys.version_info[0] > 2:
+ # Python 3 removed basestring and long
+ basestring = str
+ long = int
class PrettyPrinter(object):
"""A basic pretty-printer.
Index: gdb/python/lib/gdb/prompt.py
===================================================================
RCS file: /cvs/src/src/gdb/python/lib/gdb/prompt.py,v
retrieving revision 1.2
diff -u -r1.2 prompt.py
--- gdb/python/lib/gdb/prompt.py 4 Jan 2012 08:17:24 -0000 1.2
+++ gdb/python/lib/gdb/prompt.py 12 Nov 2012 15:51:30 -0000
@@ -98,8 +98,7 @@
functions."""
result = ''
- keys = prompt_substitutions.keys()
- keys.sort()
+ keys = sorted (prompt_substitutions.keys())
for key in keys:
result += ' \\%s\t%s\n' % (key, prompt_substitutions[key].__doc__)
result += """
Index: gdb/python/lib/gdb/command/explore.py
===================================================================
RCS file: /cvs/src/src/gdb/python/lib/gdb/command/explore.py,v
retrieving revision 1.1
diff -u -r1.1 explore.py
--- gdb/python/lib/gdb/command/explore.py 11 Apr 2012 05:50:44 -0000 1.1
+++ gdb/python/lib/gdb/command/explore.py 12 Nov 2012 15:51:30 -0000
@@ -17,7 +17,12 @@
"""Implementation of the GDB 'explore' command using the GDB Python API."""
import gdb
+import sys
+if sys.version_info[0] > 2:
+ # Python 3 renamed raw_input to input
+ raw_input = input
+
class Explorer(object):
"""Internal class which invokes other explorers."""
@@ -155,7 +160,7 @@
"""A utility function which prints that the current exploration session
is returning to the parent value. Useful when exploring values.
"""
- print "\nReturning to parent value...\n"
+ print ("\nReturning to parent value...\n")
@staticmethod
def return_to_parent_value_prompt():
@@ -170,7 +175,7 @@
"""A utility function which prints that the current exploration session
is returning to the enclosing type. Useful when exploring types.
"""
- print "\nReturning to enclosing type...\n"
+ print ("\nReturning to enclosing type...\n")
@staticmethod
def return_to_enclosing_type_prompt():
@@ -192,7 +197,7 @@
"""
print ("'%s' is a scalar value of type '%s'." %
(expr, value.type))
- print "%s = %s" % (expr, str(value))
+ print ("%s = %s" % (expr, str(value)))
if is_child:
Explorer.return_to_parent_value_prompt()
@@ -211,13 +216,13 @@
print ("%s is of an enumerated type '%s'." %
(name, str(datatype)))
else:
- print "'%s' is an enumerated type." % name
+ print ("'%s' is an enumerated type." % name)
else:
if is_child:
print ("%s is of a scalar type '%s'." %
(name, str(datatype)))
else:
- print "'%s' is a scalar type." % name
+ print ("'%s' is a scalar type." % name)
if is_child:
Explorer.return_to_enclosing_type_prompt()
@@ -268,7 +273,7 @@
try:
str(element)
except gdb.MemoryError:
- print "Cannot read value at index %d." % index
+ print ("Cannot read value at index %d." % index)
continue
Explorer.explore_expr(element_expr, element, True)
return False
@@ -338,7 +343,7 @@
element = value[index]
str(element)
except gdb.MemoryError:
- print "Cannot read value at index %d." % index
+ print ("Cannot read value at index %d." % index)
raw_input("Press enter to continue... ")
return True
@@ -352,7 +357,7 @@
See Explorer.explore_type for more information.
"""
target_type = datatype.target()
- print "%s is an array of '%s'." % (name, str(target_type))
+ print ("%s is an array of '%s'." % (name, str(target_type)))
Explorer.explore_type("the array element of %s" % name, target_type,
is_child)
@@ -371,9 +376,8 @@
if max_field_name_length < len(pair[0]):
max_field_name_length = len(pair[0])
- format_str = " {0:>%d} = {1}" % max_field_name_length
for pair in print_list:
- print format_str.format(pair[0], pair[1])
+ print ("%*s = %s" % (max_field_name_length, pair[0], pair[1]))
@staticmethod
def _get_real_field_count(fields):
@@ -447,7 +451,7 @@
print_list.append((field.name, literal_value))
CompoundExplorer._print_fields(print_list)
- print ""
+ print ("")
if has_explorable_fields:
choice = raw_input("Enter the field number of choice: ")
@@ -484,7 +488,7 @@
(name, type_desc, str(datatype)))
Explorer.return_to_enclosing_type_prompt()
else:
- print "'%s' is a %s with no fields." % (name, type_desc)
+ print ("'%s' is a %s with no fields." % (name, type_desc))
return False
if is_child:
@@ -515,7 +519,7 @@
current_choice = current_choice + 1
CompoundExplorer._print_fields(print_list)
- print ""
+ print ("")
if len(choice_to_compound_field_map) > 0:
choice = raw_input("Enter the field number of choice: ")
@@ -741,7 +745,7 @@
value = ExploreUtils.get_value_from_str(arg_str)
if value is not None:
- print "'%s' is of type '%s'." % (arg_str, str(value.type))
+ print ("'%s' is of type '%s'." % (arg_str, str(value.type)))
Explorer.explore_type(str(value.type), value.type, False)
raise gdb.GdbError(("'%s' is not a type or value in the current "
Index: gdb/python/lib/gdb/command/pretty_printers.py
===================================================================
RCS file: /cvs/src/src/gdb/python/lib/gdb/command/pretty_printers.py,v
retrieving revision 1.7
diff -u -r1.7 pretty_printers.py
--- gdb/python/lib/gdb/command/pretty_printers.py 4 Jan 2012 08:17:25 -0000 1.7
+++ gdb/python/lib/gdb/command/pretty_printers.py 12 Nov 2012 15:51:30 -0000
@@ -124,21 +124,17 @@
"""Print a list of pretty-printers."""
# A potential enhancement is to provide an option to list printers in
# "lookup order" (i.e. unsorted).
- sorted_pretty_printers = copy.copy(pretty_printers)
- sorted_pretty_printers.sort(lambda x, y:
- cmp(self.printer_name(x),
- self.printer_name(y)))
+ sorted_pretty_printers = sorted (copy.copy(pretty_printers),
+ key = self.printer_name)
for printer in sorted_pretty_printers:
name = self.printer_name(printer)
enabled = self.enabled_string(printer)
if name_re.match(name):
- print " %s%s" % (name, enabled)
+ print (" %s%s" % (name, enabled))
if (hasattr(printer, "subprinters") and
printer.subprinters is not None):
- sorted_subprinters = copy.copy(printer.subprinters)
- sorted_subprinters.sort(lambda x, y:
- cmp(self.printer_name(x),
- self.printer_name(y)))
+ sorted_subprinters = sorted (copy.copy(printer.subprinters),
+ key = self.printer_name)
for subprinter in sorted_subprinters:
if (not subname_re or
subname_re.match(subprinter.name)):
@@ -150,7 +146,7 @@
obj_name_to_match, object_re, name_re, subname_re):
"""Subroutine of invoke to simplify it."""
if printer_list and object_re.match(obj_name_to_match):
- print title
+ print (title)
self.list_pretty_printers(printer_list, name_re, subname_re)
def invoke(self, arg, from_tty):
@@ -219,7 +215,7 @@
We count subprinters individually.
"""
(enabled_count, total_count) = count_all_enabled_printers()
- print "%d of %d printers enabled" % (enabled_count, total_count)
+ print ("%d of %d printers enabled" % (enabled_count, total_count))
def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag):
@@ -301,7 +297,7 @@
state = "enabled"
else:
state = "disabled"
- print "%d %s %s" % (total, pluralize("printer", total), state)
+ print ("%d %s %s" % (total, pluralize("printer", total), state))
# Print the total list of printers currently enabled/disabled.
# This is to further assist the user in determining whether the result
^ permalink raw reply [flat|nested] 16+ messages in thread* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-12 16:06 [PATCH] Python 3 support, part 1 (non-testsuite part) Paul_Koning @ 2012-11-12 20:43 ` Tom Tromey 2012-11-12 21:37 ` Paul_Koning 0 siblings, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-11-12 20:43 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches >>>>> "Paul" == <Paul_Koning@Dell.com> writes: Paul> The attached set of patches updates the Python scripting support Paul> in GDB to add Python 3 to the existing Python 2 support. Thanks. First, I think this is definitely something we want to support. And, I think you did it the right way, by making it possible to support both versions with the same source tree. Paul> 1. Type objects have a PyVarObject header, and because of the Paul> syntax changes in the underlying macros in Python 3, you need a Paul> PyVarObject_HEAD_INIT macro to initialize those. For the same Paul> reason, calls to the tp_free method need to go through a PyObject Paul> * pointer, not a type object pointer. I think the ob_type stuff should be accessed using the Py_TYPE macro. IIUC this is new in 2.6 or 2.7, but we can easily define it conditionally. Paul> The ones that need to be different between the two versions are Paul> conditional on IS_PY3K (as suggested in the Porting Python 2 to Paul> Python 3 manual from python.org). Sounds good to me. Paul> Tested on Linux with Python version 2.4, 2.6, 2.7, 3.2, and 3.3. Paul> No regressions on any of the tests. Paul> Ok to commit? I have some comments on the patch, but nothing too serious. Paul> PyTypeObject block_object_type = { Paul> - PyObject_HEAD_INIT (NULL) Paul> - 0, /*ob_size*/ Paul> + PyVarObject_HEAD_INIT (NULL, 0) All the changes to use this macro are ok. You can put them in separately if you are so motivated (but see the note for python-internal.h). Paul> @@ -44,7 +59,11 @@ Paul> void Paul> gdbpy_initialize_py_events (void) Paul> { Paul> +#ifdef IS_PY3K Paul> + gdb_py_events.module = PyModule_Create (&EventModuleDef); Paul> +#else Paul> gdb_py_events.module = Py_InitModule ("events", NULL); Paul> +#endif I was going to suggest a convenience function here, but I see we only have two uses, so it doesn't matter all that much to me; but... Paul> +#ifndef IS_PY3K Paul> Py_INCREF (gdb_py_events.module); Paul> +#endif Why is this needed? Paul> +#ifdef IS_PY3K Paul> + Py_buffer pybuf; Paul> + if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords, Paul> + &addr_obj, &pybuf, Paul> + &length_obj)) Paul> + return NULL; At least in 2.7, if you use 's*' it appears you must call PyBuffer_Release at the appropriate moment. Paul> +++ gdb/python/py-objfile.c 12 Nov 2012 15:51:30 -0000 Paul> @@ -58,7 +58,7 @@ Paul> objfile_object *self = (objfile_object *) o; Paul> Py_XDECREF (self->printers); Paul> - self->ob_type->tp_free ((PyObject *) self); Paul> + o->ob_type->tp_free ((PyObject *) self); Paul> } One of the spots where we could write Py_TYPE (o)->tp_free ((PyObject *) self); ... with Py_TYPE conditionally defined in python-internal.h. Paul> +/* Python 2.4 does not define PyVarObject_HEAD_INIT. */ Paul> +#define PyVarObject_HEAD_INIT(type, size) \ Paul> + PyObject_HEAD_INIT(type) size, According to the docs, this wasn't introduced until Python 2.5 So rather than putting it in the HAVE_LIBPYTHON2_4 section, how about conditionally defining it like: #ifndef PyVarObject_HEAD_INIT #define ... #endif Paul> + wchar_t *progname_copy; Can we really assume a working wchar_t? Paul> + if (progsize == (size_t) -1) Paul> + { Paul> + fprintf(stderr, "Could not convert python path to string\n"); Paul> + exit (1); Paul> + } I think if Python initialization fails, we should disable Python and keep going. It should not be a fatal error. Paul> + progname_copy = PyMem_Malloc((progsize + 1) * sizeof (wchar_t)); Missing space before paren. Paul> + count = mbstowcs (progname_copy, progname, progsize + 1); Another portability question here. Paul> + if (count == (size_t) -1) { Wrong brace placement. Paul> + _PyImport_FixupBuiltin (gdb_module, "_gdb"); What does this do? Paul> +#endif Paul> #endif /* HAVE_PYTHON */ A blank line between these two would be nice. Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-12 20:43 ` Tom Tromey @ 2012-11-12 21:37 ` Paul_Koning 2012-11-13 18:53 ` Tom Tromey 0 siblings, 1 reply; 16+ messages in thread From: Paul_Koning @ 2012-11-12 21:37 UTC (permalink / raw) To: tromey; +Cc: gdb-patches On Nov 12, 2012, at 3:43 PM, Tom Tromey wrote: >>>>>> "Paul" == <Paul_Koning@Dell.com> writes: > > Paul> The attached set of patches updates the Python scripting support > Paul> in GDB to add Python 3 to the existing Python 2 support. > > Thanks. > > First, I think this is definitely something we want to support. And, I > think you did it the right way, by making it possible to support both > versions with the same source tree. Thanks! > Paul> 1. Type objects have a PyVarObject header, and because of the > Paul> syntax changes in the underlying macros in Python 3, you need a > Paul> PyVarObject_HEAD_INIT macro to initialize those. For the same > Paul> reason, calls to the tp_free method need to go through a PyObject > Paul> * pointer, not a type object pointer. > > I think the ob_type stuff should be accessed using the Py_TYPE macro. > IIUC this is new in 2.6 or 2.7, but we can easily define it > conditionally. Yes, similar to PyVarType_INIT_HEAD (with the comment you made on that). > Paul> The ones that need to be different between the two versions are > Paul> conditional on IS_PY3K (as suggested in the Porting Python 2 to > Paul> Python 3 manual from python.org). > > Sounds good to me. > > Paul> Tested on Linux with Python version 2.4, 2.6, 2.7, 3.2, and 3.3. > Paul> No regressions on any of the tests. > > Paul> Ok to commit? > > I have some comments on the patch, but nothing too serious. > > Paul> PyTypeObject block_object_type = { > Paul> - PyObject_HEAD_INIT (NULL) > Paul> - 0, /*ob_size*/ > Paul> + PyVarObject_HEAD_INIT (NULL, 0) > > All the changes to use this macro are ok. You can put them in > separately if you are so motivated (but see the note for > python-internal.h). > > Paul> @@ -44,7 +59,11 @@ > Paul> void > Paul> gdbpy_initialize_py_events (void) > Paul> { > Paul> +#ifdef IS_PY3K > Paul> + gdb_py_events.module = PyModule_Create (&EventModuleDef); > Paul> +#else > Paul> gdb_py_events.module = Py_InitModule ("events", NULL); > Paul> +#endif > > I was going to suggest a convenience function here, but I see we only > have two uses, so it doesn't matter all that much to me; but... > > Paul> +#ifndef IS_PY3K > Paul> Py_INCREF (gdb_py_events.module); > Paul> +#endif > > Why is this needed? Because PyModule_Create returns a new reference, while Py_InitModule returns a borrowed reference (bletch). > Paul> +#ifdef IS_PY3K > Paul> + Py_buffer pybuf; > > Paul> + if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords, > Paul> + &addr_obj, &pybuf, > Paul> + &length_obj)) > Paul> + return NULL; > > At least in 2.7, if you use 's*' it appears you must call > PyBuffer_Release at the appropriate moment. Thanks, yes, and it's a memory leak if you don't. There are several exits from infpy_search_memory unfortunately. Attached is a new diff for py-inferior.c. > > Paul> +++ gdb/python/py-objfile.c 12 Nov 2012 15:51:30 -0000 > Paul> @@ -58,7 +58,7 @@ > Paul> objfile_object *self = (objfile_object *) o; > > Paul> Py_XDECREF (self->printers); > Paul> - self->ob_type->tp_free ((PyObject *) self); > Paul> + o->ob_type->tp_free ((PyObject *) self); > Paul> } > > One of the spots where we could write > > Py_TYPE (o)->tp_free ((PyObject *) self); > > ... with Py_TYPE conditionally defined in python-internal.h. Or Py_TYPE (self)->tp_free (self) -- less change from the existing code. That argument doesn't need a cast, the signature is tp_free (void *). > Paul> +/* Python 2.4 does not define PyVarObject_HEAD_INIT. */ > Paul> +#define PyVarObject_HEAD_INIT(type, size) \ > Paul> + PyObject_HEAD_INIT(type) size, > > According to the docs, this wasn't introduced until Python 2.5 > So rather than putting it in the HAVE_LIBPYTHON2_4 section, how about > conditionally defining it like: > > #ifndef PyVarObject_HEAD_INIT > #define ... > #endif Will do. > Paul> + wchar_t *progname_copy; > > Can we really assume a working wchar_t? Yes, you'd expect a configure check or the like. But the header files for Python reference that type without any checks that I can see. Similarly mbstowcs(). It looks like you can't built Python 3 if those aren't defined (which makes some sense -- how else could you build a program that uses Unicode for all its strings?). > > Paul> + if (progsize == (size_t) -1) > Paul> + { > Paul> + fprintf(stderr, "Could not convert python path to string\n"); > Paul> + exit (1); > Paul> + } > > I think if Python initialization fails, we should disable Python and > keep going. It should not be a fatal error. Ok. That code was adapted from Python 3 code which does it this way. The existing code in python.c calls a whole string of API calls (like PyModule_AddStringConstant) without checking the error status from any of them. Should I add those, with the failure action being to disable Python support in GDB? > Paul> + progname_copy = PyMem_Malloc((progsize + 1) * sizeof (wchar_t)); > > Missing space before paren. > > Paul> + count = mbstowcs (progname_copy, progname, progsize + 1); > > Another portability question here. > > Paul> + if (count == (size_t) -1) { > > Wrong brace placement. > > Paul> + _PyImport_FixupBuiltin (gdb_module, "_gdb"); > > What does this do? It adds _gdb to the known builtin (linked in) modules, so that the subsequent "import _gdb" will work. > Paul> +#endif > Paul> #endif /* HAVE_PYTHON */ > > A blank line between these two would be nice. Ok. > > Tom Index: py-inferior.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-inferior.c,v retrieving revision 1.25 diff -u -r1.25 py-inferior.c --- py-inferior.c 22 Aug 2012 15:17:21 -0000 1.25 +++ py-inferior.c 12 Nov 2012 21:03:41 -0000 @@ -454,9 +454,14 @@ membuf_obj->addr = addr; membuf_obj->length = length; +#ifdef IS_PY3K + result = PyMemoryView_FromObject ((PyObject *) membuf_obj); +#else result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0, Py_END_OF_BUFFER); +#endif Py_DECREF (membuf_obj); + return result; } @@ -476,12 +481,22 @@ PyObject *addr_obj, *length_obj = NULL; volatile struct gdb_exception except; static char *keywords[] = { "address", "buffer", "length", NULL }; +#ifdef IS_PY3K + Py_buffer pybuf; + if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords, + &addr_obj, &pybuf, + &length_obj)) + return NULL; + buffer = pybuf.buf; + buf_len = pybuf.len; +#else if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords, &addr_obj, &buffer, &buf_len, &length_obj)) return NULL; +#endif TRY_CATCH (except, RETURN_MASK_ALL) { @@ -502,6 +517,10 @@ } GDB_PY_HANDLE_EXCEPTION (except); +#ifdef IS_PY3K + PyBuffer_Release (pybuf); +#endif + if (error) return NULL; @@ -528,6 +547,23 @@ pulongest (membuf_obj->length)); } +#ifdef IS_PY3K +static int +get_buffer (PyObject *self, Py_buffer *buf, int flags) +{ + membuf_object *membuf_obj = (membuf_object *) self; + int ret; + + ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer, + membuf_obj->length, 0, + PyBUF_CONTIG); + buf->format = "c"; + + return ret; +} + +#else + static Py_ssize_t get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr) { @@ -572,6 +608,8 @@ return ret; } +#endif /* IS_PY3K */ + /* Implementation of gdb.search_memory (address, length, pattern). ADDRESS is the address to start the search. LENGTH specifies the scope of the @@ -585,17 +623,41 @@ { CORE_ADDR start_addr, length; static char *keywords[] = { "address", "length", "pattern", NULL }; - PyObject *pattern, *start_addr_obj, *length_obj; + PyObject *start_addr_obj, *length_obj; volatile struct gdb_exception except; Py_ssize_t pattern_size; const void *buffer; CORE_ADDR found_addr; int found = 0; +#ifdef IS_PY3K + Py_buffer pybuf; - if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords, + if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords, &start_addr_obj, &length_obj, + &pybuf)) + return NULL; + + buffer = pybuf.buf; + pattern_size = pybuf.len; +#else + PyObject *pattern; + + if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords, + &start_addr_obj, &length_obj, &pattern)) + return NULL; + + if (!PyObject_CheckReadBuffer (pattern)) + { + PyErr_SetString (PyExc_RuntimeError, + _("The pattern is not a Python buffer.")); + + return NULL; + } + + if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1) return NULL; +#endif if (get_addr_from_python (start_addr_obj, &start_addr) && get_addr_from_python (length_obj, &length)) @@ -604,6 +666,10 @@ { PyErr_SetString (PyExc_ValueError, _("Search range is empty.")); + +#ifdef IS_PY3K + PyBuffer_Release (pybuf); +#endif return NULL; } /* Watch for overflows. */ @@ -613,23 +679,15 @@ PyErr_SetString (PyExc_ValueError, _("The search range is too large.")); +#ifdef IS_PY3K + PyBuffer_Release (pybuf); +#endif return NULL; } } else return NULL; - if (!PyObject_CheckReadBuffer (pattern)) - { - PyErr_SetString (PyExc_RuntimeError, - _("The pattern is not a Python buffer.")); - - return NULL; - } - - if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1) - return NULL; - TRY_CATCH (except, RETURN_MASK_ALL) { found = target_search_memory (start_addr, length, @@ -638,6 +696,10 @@ } GDB_PY_HANDLE_EXCEPTION (except); +#ifdef IS_PY3K + PyBuffer_Release (pybuf); +#endif + if (found) return PyLong_FromLong (found_addr); else @@ -777,8 +839,7 @@ static PyTypeObject inferior_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Inferior", /* tp_name */ sizeof (inferior_object), /* tp_basicsize */ 0, /* tp_itemsize */ @@ -817,6 +878,13 @@ 0 /* tp_alloc */ }; +#ifdef IS_PY3K +static PyBufferProcs buffer_procs = { + get_buffer +}; + +#else + /* Python doesn't provide a decent way to get compatibility here. */ #if HAVE_LIBPYTHON2_4 #define CHARBUFFERPROC_NAME getcharbufferproc @@ -832,10 +900,10 @@ Python 2.5. */ (CHARBUFFERPROC_NAME) get_char_buffer }; +#endif /* IS_PY3K */ static PyTypeObject membuf_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Membuf", /*tp_name*/ sizeof (membuf_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-12 21:37 ` Paul_Koning @ 2012-11-13 18:53 ` Tom Tromey 2012-11-13 19:02 ` Paul_Koning 0 siblings, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-11-13 18:53 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches >>>>> "Paul" == <Paul_Koning@Dell.com> writes: Paul> Because PyModule_Create returns a new reference, while Py_InitModule Paul> returns a borrowed reference (bletch). Oh, yeah, it is obvious now :) Thanks. [...] Paul> Or Py_TYPE (self)->tp_free (self) -- less change from the existing Paul> code. That argument doesn't need a cast, the signature is tp_free Paul> (void *). Oops, yeah, that is what I meant. Paul> + wchar_t *progname_copy; Tom> Can we really assume a working wchar_t? Paul> Yes, you'd expect a configure check or the like. But the header files Paul> for Python reference that type without any checks that I can see. Paul> Similarly mbstowcs(). It looks like you can't built Python 3 if those Paul> aren't defined (which makes some sense -- how else could you build a Paul> program that uses Unicode for all its strings?). Ok, I think that is sufficient. If Python ever adds checks, and we hit such a such a system, we can fix it up then. It is a little weird since wchar_t isn't guaranteed to have anything to do with Unicode. But I assume they know what they are doing. Paul> Ok. That code was adapted from Python 3 code which does it this way. Paul> The existing code in python.c calls a whole string of API calls (like Paul> PyModule_AddStringConstant) without checking the error status from any Paul> of them. Should I add those, with the failure action being to disable Paul> Python support in GDB? I'm not sure what to do about those. I guess failing gracefully would be better than what we do now. FWIW I'm not sure we really have a way to disable Python at runtime yet. And to be clear, I don't expect you to add this as part of your patch. Mostly I just want to avoid an 'exit' on a failure to initialize -- it is better for gdb to try to limp along in this situation. Paul> Index: py-inferior.c [...] Paul> GDB_PY_HANDLE_EXCEPTION (except); Paul> +#ifdef IS_PY3K Paul> + PyBuffer_Release (pybuf); Paul> +#endif GDB_PY_HANDLE_EXCEPTION can return, so cleaning up has to be handled there as well somehow. Maybe this is an issue in the other spot, too, I couldn't tell immediately. Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 18:53 ` Tom Tromey @ 2012-11-13 19:02 ` Paul_Koning 2012-11-13 19:12 ` Tom Tromey 0 siblings, 1 reply; 16+ messages in thread From: Paul_Koning @ 2012-11-13 19:02 UTC (permalink / raw) To: tromey; +Cc: gdb-patches On Nov 13, 2012, at 1:53 PM, Tom Tromey wrote: >>>>>> "Paul" == <Paul_Koning@Dell.com> writes: > > ...Tom> Can we really assume a working wchar_t? > > Paul> Yes, you'd expect a configure check or the like. But the header files > Paul> for Python reference that type without any checks that I can see. > Paul> Similarly mbstowcs(). It looks like you can't built Python 3 if those > Paul> aren't defined (which makes some sense -- how else could you build a > Paul> program that uses Unicode for all its strings?). > > Ok, I think that is sufficient. > If Python ever adds checks, and we hit such a such a system, we can fix > it up then. > > It is a little weird since wchar_t isn't guaranteed to have anything to > do with Unicode. But I assume they know what they are doing. It seems that way. Python uses its own type internally if it has to, but uses wchar_t if that is suitable for storing Unicode in the way it wants to store it. And the PySys_SetArgv call is specifically defined to take wchar_t arguments -- not the Python Unicode type that is used elsewhere. > > Paul> Ok. That code was adapted from Python 3 code which does it this way. > Paul> The existing code in python.c calls a whole string of API calls (like > Paul> PyModule_AddStringConstant) without checking the error status from any > Paul> of them. Should I add those, with the failure action being to disable > Paul> Python support in GDB? > > I'm not sure what to do about those. I guess failing gracefully would > be better than what we do now. > > FWIW I'm not sure we really have a way to disable Python at runtime yet. > And to be clear, I don't expect you to add this as part of your patch. > Mostly I just want to avoid an 'exit' on a failure to initialize -- it > is better for gdb to try to limp along in this situation. Ok, I'll take out the exit and leave the error handling for a separate patch. > > Paul> Index: py-inferior.c > [...] > Paul> GDB_PY_HANDLE_EXCEPTION (except); > > Paul> +#ifdef IS_PY3K > Paul> + PyBuffer_Release (pybuf); > Paul> +#endif > > GDB_PY_HANDLE_EXCEPTION can return, so cleaning up has to be handled > there as well somehow. > > Maybe this is an issue in the other spot, too, I couldn't tell > immediately. Oops. I suppose I can do this via the "cleanup" mechanism, right? paul > > Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 19:02 ` Paul_Koning @ 2012-11-13 19:12 ` Tom Tromey 2012-11-13 19:26 ` Paul_Koning 0 siblings, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-11-13 19:12 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches >>>>> "Paul" == <Paul_Koning@Dell.com> writes: Paul> Oops. I suppose I can do this via the "cleanup" mechanism, right? You'd have to insert a do_cleanups call in there somehow, but at that point is just as easy to just call the python function directly instead. Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 19:12 ` Tom Tromey @ 2012-11-13 19:26 ` Paul_Koning 2012-11-13 19:43 ` Tom Tromey 0 siblings, 1 reply; 16+ messages in thread From: Paul_Koning @ 2012-11-13 19:26 UTC (permalink / raw) To: tromey; +Cc: gdb-patches On Nov 13, 2012, at 2:11 PM, Tom Tromey wrote: >>>>>> "Paul" == <Paul_Koning@Dell.com> writes: > > Paul> Oops. I suppose I can do this via the "cleanup" mechanism, right? > > You'd have to insert a do_cleanups call in there somehow, but at that > point is just as easy to just call the python function directly instead. > > Tom What I meant is that if I set the PyBuffer_Release as the cleanup function, it will be called if the handle_exception machinery gets an exception and returns out from under me. Right? paul ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 19:26 ` Paul_Koning @ 2012-11-13 19:43 ` Tom Tromey 2012-11-13 19:56 ` Paul_Koning 0 siblings, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-11-13 19:43 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches >>>>> "Paul" == <Paul_Koning@Dell.com> writes: Paul> What I meant is that if I set the PyBuffer_Release as the cleanup Paul> function, it will be called if the handle_exception machinery gets an Paul> exception and returns out from under me. Right? Yeah, if you make the cleanup inside the try-catch. But then you have to explicitly call do_cleanups or discard_cleanups as well. Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 19:43 ` Tom Tromey @ 2012-11-13 19:56 ` Paul_Koning 2012-11-13 20:24 ` Tom Tromey 0 siblings, 1 reply; 16+ messages in thread From: Paul_Koning @ 2012-11-13 19:56 UTC (permalink / raw) To: tromey; +Cc: gdb-patches On Nov 13, 2012, at 2:42 PM, Tom Tromey wrote: >>>>>> "Paul" == <Paul_Koning@Dell.com> writes: > > Paul> What I meant is that if I set the PyBuffer_Release as the cleanup > Paul> function, it will be called if the handle_exception machinery gets an > Paul> exception and returns out from under me. Right? > > Yeah, if you make the cleanup inside the try-catch. > But then you have to explicitly call do_cleanups or discard_cleanups as > well. > > Tom Does that mean that a make cleanup done before the try-catch is not in effect within the try-catch? paul ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 19:56 ` Paul_Koning @ 2012-11-13 20:24 ` Tom Tromey 2012-11-14 16:03 ` Paul_Koning 0 siblings, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-11-13 20:24 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches Paul> Does that mean that a make cleanup done before the try-catch is not in Paul> effect within the try-catch? Yeah. The try-catch resets the cleanup chain. I find that cleanups are a lot easier to reason about when I treat them like C++ destructors -- make them be block scoped as much as possible. Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-13 20:24 ` Tom Tromey @ 2012-11-14 16:03 ` Paul_Koning 2012-11-19 16:49 ` Tom Tromey 0 siblings, 1 reply; 16+ messages in thread From: Paul_Koning @ 2012-11-14 16:03 UTC (permalink / raw) To: tromey; +Cc: gdb-patches Here is an updated patch which I believe addresses all the comments. Should I add a NEWS entry for the Python 3 support? Ok to commit? Also, is the testsuite part ok? paul 2012-11-14 Paul Koning <paul_koning@dell.com> Add support for Python 3. * varobj.c (value_get_print_value): Use python_string_to_target_string. * python/py-block.c: Use PyVarObject_HEAD_INIT in initialization of type objects. * python/py-breakpoint.c: Ditto. * python/py-cmd.c: Ditto. * python/py-event.c: Ditto. * python/py-event.h: Ditto. * python/py-evtregistry.c: Ditto. * python/py-finishbreakpoint.c: Ditto. * python/py-frame.c: Ditto. * python/py-function.c: Ditto. * python/py-infthread.c: Ditto. * python/py-lazy-string.c: Ditto. * python/py-progspace.c: Ditto. * /python/py-symbol.c: Ditto. * python/py-evts.c: (gdbpy_initialize_py_events): Add module initialization for Python 3. * python/py-inferior.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (infpy_read_memory): Return memoryview object if Python 3. (infpy_write_memory): Use "s*" operand parsing code for Python 3. (infpy_search_memory): Ditto. (get_buffer): New function for Python 3. * python/py-objfile.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (objfpy_dealloc): Use Py_TYPE to call tp_free. * python/py-param.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (get_attr): Use PyUnicode_CompareWithASCIIString if Python 3. (set_attr): Ditto. * python/py-prettyprint.c (print_string_repr): use PyBytes methods instead of PyString methods if Python 3. (print_children): Skip push_dummy_python_frame call if Python 3. * python/py-symtab.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (salpy_dealloc): Use Py_TYPE to call tp_free. * python/py-type.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (field_dealloc): Use Py_TYPE to call tp_free. (typy_dealloc): Ditto. (type_object_as_number): Adjust struct initializations for differences in layout for Python 2 vs. Python 3. * python/py-utils.c (python_string_to_unicode): Omit non-Unicode string case for Python 3. (unicode_to_encoded_python_string): Shorten code (no functional change). (python_string_to_target_python_string): Comment that in Python 3 returned value is a Python "bytes" type. (gdbpy_is_string): Omit non-Unicode string check in Python 3. (gdb_py_object_from_longest): Omit non-long integer case in Python 3. (gdb_py_object_from_ulongest): Ditto. * python/py-value.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (valpy_dealloc): Use Py_TYPE to call tp_free. (valpy_int): Omit function if Python 3. (convert_value_from_python): Use "%S" format (Python object as a string) if Python 3. (value_object_as_number): Adjust struct initializations for differences in layout for Python 2 vs. Python 3. * python/python-config.py: Adjust syntax for Python 3 compatibility. Include "sys.abiflags" string as part of python library name, if that attribute exists (Python 3). * python/python-internal.h (IS_PY3): Define if Python 3. (Py_TPFLAGS_HAVE_ITER, Py_TPFLAGS_CHECKTYPES): Define with placeholder value if Python 3. (PyInt_Check, PyInt_FromLong, PyInt_AsLong, PyString_FromString, PyString_Decode, PyString_FromFormat, PyString_Check): Define as analogous Python 3 API function if Python 3. (PyVarObject_HEAD_INIT): Define if not already defined. (Py_TYPE): Ditto. * python/python.c (eval_python_command): Omit Py_FlushLine call if Python 3. (_initialize_python): Convert argc to wchar_t** if Python 3. Add module initialization for Python 3. (finish_python_initialization): Pass wchar_t * argument to PySys_SetPath if Python 3. * python/lib/gdb/__init__.py: Define "reload" if Python 3. (_GdbFile): New class for common output file behavior. (GdbOutFile): Subclass from _GdbFile. (GdbOutputErrorFile): Ditto. (auto_load_packages): Adjust syntax for Python 3 compatibility. * python/lib/gdb/printing.py: Define basestr and int if Python 3. * python/lib/gdb/prompt.py: Use sorted() function rather than sort() method. * python/lib/gdb/command/explore.py: Define raw_input if Python 3. Adjust syntax for Python 3 compatibility. * python/lib/gdb/command/pretty_printers.py: Use sorted() function rather than sort() method. Adjust syntax for Python 3 compatibility. * doc/gdb.texinfo (Inferior.read_memory): Mention that the return value is a memoryview object if Python 3. Index: gdb/varobj.c =================================================================== RCS file: /cvs/src/src/gdb/varobj.c,v retrieving revision 1.200 diff -u -r1.200 varobj.c --- gdb/varobj.c 6 Aug 2012 18:44:44 -0000 1.200 +++ gdb/varobj.c 14 Nov 2012 15:57:14 -0000 @@ -2910,12 +2910,10 @@ string_print. Otherwise just return the extracted string as a value. */ - PyObject *py_str - = python_string_to_target_python_string (output); + char *s = python_string_to_target_string (output); - if (py_str) + if (s) { - char *s = PyString_AsString (py_str); char *hint; hint = gdbpy_get_display_hint (value_formatter); @@ -2926,10 +2924,10 @@ xfree (hint); } - len = PyString_Size (py_str); + len = strlen (s); thevalue = xmemdup (s, len + 1, len + 1); type = builtin_type (gdbarch)->builtin_char; - Py_DECREF (py_str); + xfree (s); if (!string_print) { Index: gdb/doc/gdb.texinfo =================================================================== RCS file: /cvs/src/src/gdb/doc/gdb.texinfo,v retrieving revision 1.1024 diff -u -r1.1024 gdb.texinfo --- gdb/doc/gdb.texinfo 13 Nov 2012 21:19:10 -0000 1.1024 +++ gdb/doc/gdb.texinfo 14 Nov 2012 15:57:17 -0000 @@ -24106,7 +24106,8 @@ Read @var{length} bytes of memory from the inferior, starting at @var{address}. Returns a buffer object, which behaves much like an array or a string. It can be modified and given to the -@code{Inferior.write_memory} function. +@code{Inferior.write_memory} function. In @code{Python} 3, the return +value is a @code{memoryview} object. @end defun @findex Inferior.write_memory Index: gdb/python/py-block.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-block.c,v retrieving revision 1.12 diff -u -r1.12 py-block.c --- gdb/python/py-block.c 10 May 2012 19:50:09 -0000 1.12 +++ gdb/python/py-block.c 14 Nov 2012 15:57:17 -0000 @@ -475,8 +475,7 @@ }; PyTypeObject block_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Block", /*tp_name*/ sizeof (block_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -516,8 +515,7 @@ }; static PyTypeObject block_syms_iterator_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.BlockIterator", /*tp_name*/ sizeof (block_syms_iterator_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-breakpoint.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-breakpoint.c,v retrieving revision 1.34 diff -u -r1.34 py-breakpoint.c --- gdb/python/py-breakpoint.c 14 May 2012 15:38:40 -0000 1.34 +++ gdb/python/py-breakpoint.c 14 Nov 2012 15:57:17 -0000 @@ -981,8 +981,7 @@ PyTypeObject breakpoint_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Breakpoint", /*tp_name*/ sizeof (breakpoint_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-cmd.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-cmd.c,v retrieving revision 1.21 diff -u -r1.21 py-cmd.c --- gdb/python/py-cmd.c 13 Jun 2012 15:47:16 -0000 1.21 +++ gdb/python/py-cmd.c 14 Nov 2012 15:57:17 -0000 @@ -607,8 +607,7 @@ static PyTypeObject cmdpy_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Command", /*tp_name*/ sizeof (cmdpy_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-event.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-event.c,v retrieving revision 1.5 diff -u -r1.5 py-event.c --- gdb/python/py-event.c 8 Nov 2012 19:38:43 -0000 1.5 +++ gdb/python/py-event.c 14 Nov 2012 15:57:17 -0000 @@ -24,7 +24,7 @@ evpy_dealloc (PyObject *self) { Py_XDECREF (((event_object *) self)->dict); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } PyObject * @@ -143,8 +143,7 @@ PyTypeObject event_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Event", /* tp_name */ sizeof (event_object), /* tp_basicsize */ 0, /* tp_itemsize */ Index: gdb/python/py-event.h =================================================================== RCS file: /cvs/src/src/gdb/python/py-event.h,v retrieving revision 1.6 diff -u -r1.6 py-event.h --- gdb/python/py-event.h 8 Nov 2012 19:38:43 -0000 1.6 +++ gdb/python/py-event.h 14 Nov 2012 15:57:17 -0000 @@ -48,8 +48,7 @@ \ qual PyTypeObject name##_event_object_type = \ { \ - PyObject_HEAD_INIT (NULL) \ - 0, /* ob_size */ \ + PyVarObject_HEAD_INIT (NULL, 0) \ py_path, /* tp_name */ \ sizeof (event_object), /* tp_basicsize */ \ 0, /* tp_itemsize */ \ Index: gdb/python/py-evtregistry.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-evtregistry.c,v retrieving revision 1.3 diff -u -r1.3 py-evtregistry.c --- gdb/python/py-evtregistry.c 4 Jan 2012 08:17:25 -0000 1.3 +++ gdb/python/py-evtregistry.c 14 Nov 2012 15:57:17 -0000 @@ -97,7 +97,7 @@ evregpy_dealloc (PyObject *self) { Py_XDECREF (((eventregistry_object *) self)->callbacks); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Initialize the Python event registry code. */ @@ -131,8 +131,7 @@ static PyTypeObject eventregistry_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.EventRegistry", /* tp_name */ sizeof (eventregistry_object), /* tp_basicsize */ 0, /* tp_itemsize */ Index: gdb/python/py-evts.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-evts.c,v retrieving revision 1.5 diff -u -r1.5 py-evts.c --- gdb/python/py-evts.c 8 Nov 2012 19:38:43 -0000 1.5 +++ gdb/python/py-evts.c 14 Nov 2012 15:57:17 -0000 @@ -20,6 +20,21 @@ #include "defs.h" #include "py-events.h" +#ifdef IS_PY3K +static struct PyModuleDef EventModuleDef = +{ + PyModuleDef_HEAD_INIT, + "gdb.events", + NULL, + -1, + NULL, + NULL, + NULL, + NULL, + NULL +}; +#endif + /* Initialize python events. */ static int @@ -45,7 +60,11 @@ void gdbpy_initialize_py_events (void) { +#ifdef IS_PY3K + gdb_py_events.module = PyModule_Create (&EventModuleDef); +#else gdb_py_events.module = Py_InitModule ("events", NULL); +#endif if (!gdb_py_events.module) goto fail; @@ -62,7 +81,9 @@ if (add_new_registry (&gdb_py_events.new_objfile, "new_objfile") < 0) goto fail; +#ifndef IS_PY3K Py_INCREF (gdb_py_events.module); +#endif if (PyModule_AddObject (gdb_module, "events", (PyObject *) gdb_py_events.module) < 0) Index: gdb/python/py-finishbreakpoint.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-finishbreakpoint.c,v retrieving revision 1.8 diff -u -r1.8 py-finishbreakpoint.c --- gdb/python/py-finishbreakpoint.c 9 Nov 2012 19:58:03 -0000 1.8 +++ gdb/python/py-finishbreakpoint.c 14 Nov 2012 15:57:17 -0000 @@ -425,8 +425,7 @@ static PyTypeObject finish_breakpoint_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.FinishBreakpoint", /*tp_name*/ sizeof (struct finish_breakpoint_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-frame.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-frame.c,v retrieving revision 1.26 diff -u -r1.26 py-frame.c --- gdb/python/py-frame.c 7 Feb 2012 19:47:15 -0000 1.26 +++ gdb/python/py-frame.c 14 Nov 2012 15:57:17 -0000 @@ -662,8 +662,7 @@ }; PyTypeObject frame_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Frame", /* tp_name */ sizeof (frame_object), /* tp_basicsize */ 0, /* tp_itemsize */ Index: gdb/python/py-function.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-function.c,v retrieving revision 1.12 diff -u -r1.12 py-function.c --- gdb/python/py-function.c 4 Jan 2012 08:17:25 -0000 1.12 +++ gdb/python/py-function.c 14 Nov 2012 15:57:17 -0000 @@ -208,8 +208,7 @@ static PyTypeObject fnpy_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Function", /*tp_name*/ sizeof (PyObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-inferior.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-inferior.c,v retrieving revision 1.26 diff -u -r1.26 py-inferior.c --- gdb/python/py-inferior.c 9 Nov 2012 19:58:03 -0000 1.26 +++ gdb/python/py-inferior.c 14 Nov 2012 15:57:17 -0000 @@ -454,9 +454,14 @@ membuf_obj->addr = addr; membuf_obj->length = length; +#ifdef IS_PY3K + result = PyMemoryView_FromObject ((PyObject *) membuf_obj); +#else result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0, Py_END_OF_BUFFER); +#endif Py_DECREF (membuf_obj); + return result; } @@ -476,12 +481,22 @@ PyObject *addr_obj, *length_obj = NULL; volatile struct gdb_exception except; static char *keywords[] = { "address", "buffer", "length", NULL }; +#ifdef IS_PY3K + Py_buffer pybuf; + if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords, + &addr_obj, &pybuf, + &length_obj)) + return NULL; + buffer = pybuf.buf; + buf_len = pybuf.len; +#else if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords, &addr_obj, &buffer, &buf_len, &length_obj)) return NULL; +#endif TRY_CATCH (except, RETURN_MASK_ALL) { @@ -500,8 +515,14 @@ } write_memory_with_notification (addr, buffer, length); } + if (except.reason < 0) + PyBuffer_Release (&pybuf); GDB_PY_HANDLE_EXCEPTION (except); +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif + if (error) return NULL; @@ -513,7 +534,7 @@ mbpy_dealloc (PyObject *self) { xfree (((membuf_object *) self)->buffer); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Return a description of the Membuf object. */ @@ -528,6 +549,23 @@ pulongest (membuf_obj->length)); } +#ifdef IS_PY3K +static int +get_buffer (PyObject *self, Py_buffer *buf, int flags) +{ + membuf_object *membuf_obj = (membuf_object *) self; + int ret; + + ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer, + membuf_obj->length, 0, + PyBUF_CONTIG); + buf->format = "c"; + + return ret; +} + +#else + static Py_ssize_t get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr) { @@ -572,6 +610,8 @@ return ret; } +#endif /* IS_PY3K */ + /* Implementation of gdb.search_memory (address, length, pattern). ADDRESS is the address to start the search. LENGTH specifies the scope of the @@ -585,17 +625,41 @@ { CORE_ADDR start_addr, length; static char *keywords[] = { "address", "length", "pattern", NULL }; - PyObject *pattern, *start_addr_obj, *length_obj; + PyObject *start_addr_obj, *length_obj; volatile struct gdb_exception except; Py_ssize_t pattern_size; const void *buffer; CORE_ADDR found_addr; int found = 0; +#ifdef IS_PY3K + Py_buffer pybuf; - if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords, + if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords, &start_addr_obj, &length_obj, + &pybuf)) + return NULL; + + buffer = pybuf.buf; + pattern_size = pybuf.len; +#else + PyObject *pattern; + + if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords, + &start_addr_obj, &length_obj, &pattern)) + return NULL; + + if (!PyObject_CheckReadBuffer (pattern)) + { + PyErr_SetString (PyExc_RuntimeError, + _("The pattern is not a Python buffer.")); + + return NULL; + } + + if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1) return NULL; +#endif if (get_addr_from_python (start_addr_obj, &start_addr) && get_addr_from_python (length_obj, &length)) @@ -604,6 +668,10 @@ { PyErr_SetString (PyExc_ValueError, _("Search range is empty.")); + +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif return NULL; } /* Watch for overflows. */ @@ -613,23 +681,15 @@ PyErr_SetString (PyExc_ValueError, _("The search range is too large.")); +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif return NULL; } } else return NULL; - if (!PyObject_CheckReadBuffer (pattern)) - { - PyErr_SetString (PyExc_RuntimeError, - _("The pattern is not a Python buffer.")); - - return NULL; - } - - if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1) - return NULL; - TRY_CATCH (except, RETURN_MASK_ALL) { found = target_search_memory (start_addr, length, @@ -638,6 +698,10 @@ } GDB_PY_HANDLE_EXCEPTION (except); +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif + if (found) return PyLong_FromLong (found_addr); else @@ -777,8 +841,7 @@ static PyTypeObject inferior_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Inferior", /* tp_name */ sizeof (inferior_object), /* tp_basicsize */ 0, /* tp_itemsize */ @@ -817,6 +880,13 @@ 0 /* tp_alloc */ }; +#ifdef IS_PY3K +static PyBufferProcs buffer_procs = { + get_buffer +}; + +#else + /* Python doesn't provide a decent way to get compatibility here. */ #if HAVE_LIBPYTHON2_4 #define CHARBUFFERPROC_NAME getcharbufferproc @@ -832,10 +902,10 @@ Python 2.5. */ (CHARBUFFERPROC_NAME) get_char_buffer }; +#endif /* IS_PY3K */ static PyTypeObject membuf_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Membuf", /*tp_name*/ sizeof (membuf_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-infthread.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-infthread.c,v retrieving revision 1.7 diff -u -r1.7 py-infthread.c --- gdb/python/py-infthread.c 18 May 2012 21:02:52 -0000 1.7 +++ gdb/python/py-infthread.c 14 Nov 2012 15:57:17 -0000 @@ -59,7 +59,7 @@ thpy_dealloc (PyObject *self) { Py_DECREF (((thread_object *) self)->inf_obj); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } static PyObject * @@ -301,8 +301,7 @@ static PyTypeObject thread_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.InferiorThread", /*tp_name*/ sizeof (thread_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-lazy-string.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-lazy-string.c,v retrieving revision 1.12 diff -u -r1.12 py-lazy-string.c --- gdb/python/py-lazy-string.c 1 Mar 2012 21:06:54 -0000 1.12 +++ gdb/python/py-lazy-string.c 14 Nov 2012 15:57:17 -0000 @@ -216,8 +216,7 @@ }; static PyTypeObject lazy_string_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.LazyString", /*tp_name*/ sizeof (lazy_string_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-objfile.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-objfile.c,v retrieving revision 1.12 diff -u -r1.12 py-objfile.c --- gdb/python/py-objfile.c 12 Nov 2012 17:41:57 -0000 1.12 +++ gdb/python/py-objfile.c 14 Nov 2012 15:57:17 -0000 @@ -62,7 +62,7 @@ Py_XDECREF (self->printers); Py_XDECREF (self->type_printers); - self->ob_type->tp_free ((PyObject *) self); + Py_TYPE (self)->tp_free (self); } static PyObject * @@ -277,8 +277,7 @@ static PyTypeObject objfile_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Objfile", /*tp_name*/ sizeof (objfile_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-param.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-param.c,v retrieving revision 1.15 diff -u -r1.15 py-param.c --- gdb/python/py-param.c 4 Jan 2012 08:17:25 -0000 1.15 +++ gdb/python/py-param.c 14 Nov 2012 15:57:17 -0000 @@ -102,7 +102,11 @@ get_attr (PyObject *obj, PyObject *attr_name) { if (PyString_Check (attr_name) +#ifdef IS_PY3K + && ! PyUnicode_CompareWithASCIIString (attr_name, "value")) +#else && ! strcmp (PyString_AsString (attr_name), "value")) +#endif { parmpy_object *self = (parmpy_object *) obj; @@ -276,7 +280,11 @@ set_attr (PyObject *obj, PyObject *attr_name, PyObject *val) { if (PyString_Check (attr_name) +#ifdef IS_PY3K + && ! PyUnicode_CompareWithASCIIString (attr_name, "value")) +#else && ! strcmp (PyString_AsString (attr_name), "value")) +#endif { if (!val) { @@ -773,8 +781,7 @@ static PyTypeObject parmpy_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Parameter", /*tp_name*/ sizeof (parmpy_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-prettyprint.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-prettyprint.c,v retrieving revision 1.28 diff -u -r1.28 py-prettyprint.c --- gdb/python/py-prettyprint.c 13 Sep 2012 21:49:31 -0000 1.28 +++ gdb/python/py-prettyprint.c 14 Nov 2012 15:57:17 -0000 @@ -348,8 +348,13 @@ struct type *type; make_cleanup_py_decref (string); +#ifdef IS_PY3K + output = (gdb_byte *) PyBytes_AS_STRING (string); + length = PyBytes_GET_SIZE (string); +#else output = PyString_AsString (string); length = PyString_Size (string); +#endif type = builtin_type (gdbarch)->builtin_char; if (hint && !strcmp (hint, "string")) @@ -383,6 +388,7 @@ return result; } +#ifndef IS_PY3K static void py_restore_tstate (void *p) { @@ -458,6 +464,7 @@ make_cleanup (py_restore_tstate, frame->f_back); return (PyObject *) frame; } +#endif /* Helper for apply_val_pretty_printer that formats children of the printer, if any exist. If is_py_none is true, then nothing has @@ -471,7 +478,10 @@ { int is_map, is_array, done_flag, pretty; unsigned int i; - PyObject *children, *iter, *frame; + PyObject *children, *iter; +#ifndef IS_PY3K + PyObject *frame; +#endif struct cleanup *cleanups; if (! PyObject_HasAttr (printer, gdbpy_children_cst)) @@ -515,6 +525,7 @@ /* Manufacture a dummy Python frame to work around Python 2.4 bug, where it insists on having a non-NULL tstate->frame when a generator is called. */ +#ifndef IS_PY3K frame = push_dummy_python_frame (); if (!frame) { @@ -522,6 +533,7 @@ goto done; } make_cleanup_py_decref (frame); +#endif done_flag = 0; for (i = 0; i < options->print_max; ++i) Index: gdb/python/py-progspace.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-progspace.c,v retrieving revision 1.10 diff -u -r1.10 py-progspace.c --- gdb/python/py-progspace.c 12 Nov 2012 17:41:57 -0000 1.10 +++ gdb/python/py-progspace.c 14 Nov 2012 15:57:17 -0000 @@ -70,7 +70,7 @@ Py_XDECREF (ps_self->printers); Py_XDECREF (ps_self->type_printers); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } static PyObject * @@ -264,8 +264,7 @@ static PyTypeObject pspace_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Progspace", /*tp_name*/ sizeof (pspace_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-symbol.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-symbol.c,v retrieving revision 1.15 diff -u -r1.15 py-symbol.c --- gdb/python/py-symbol.c 15 Oct 2012 15:20:26 -0000 1.15 +++ gdb/python/py-symbol.c 14 Nov 2012 15:57:17 -0000 @@ -561,8 +561,7 @@ }; PyTypeObject symbol_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Symbol", /*tp_name*/ sizeof (symbol_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-symtab.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-symtab.c,v retrieving revision 1.12 diff -u -r1.12 py-symtab.c --- gdb/python/py-symtab.c 18 Oct 2012 20:14:45 -0000 1.12 +++ gdb/python/py-symtab.c 14 Nov 2012 15:57:17 -0000 @@ -307,7 +307,7 @@ Py_DECREF (self_sal->symtab); xfree (self_sal->sal); - self_sal->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Given a sal, and a sal_object that has previously been allocated @@ -539,8 +539,7 @@ }; static PyTypeObject symtab_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Symtab", /*tp_name*/ sizeof (symtab_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -590,8 +589,7 @@ }; static PyTypeObject sal_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Symtab_and_line", /*tp_name*/ sizeof (sal_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-type.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-type.c,v retrieving revision 1.44 diff -u -r1.44 py-type.c --- gdb/python/py-type.c 12 Nov 2012 17:26:21 -0000 1.44 +++ gdb/python/py-type.c 14 Nov 2012 15:57:17 -0000 @@ -123,7 +123,7 @@ field_object *f = (field_object *) obj; Py_XDECREF (f->dict); - f->ob_type->tp_free (obj); + Py_TYPE (obj)->tp_free (obj); } static PyObject * @@ -1262,7 +1262,7 @@ if (type->next) type->next->prev = type->prev; - type->ob_type->tp_free (type); + Py_TYPE (type)->tp_free (type); } /* Return number of fields ("length" of the field dictionary). */ @@ -1657,7 +1657,9 @@ NULL, /* nb_add */ NULL, /* nb_subtract */ NULL, /* nb_multiply */ +#ifndef IS_PY3K NULL, /* nb_divide */ +#endif NULL, /* nb_remainder */ NULL, /* nb_divmod */ NULL, /* nb_power */ @@ -1671,12 +1673,19 @@ NULL, /* nb_and */ NULL, /* nb_xor */ NULL, /* nb_or */ +#ifdef IS_PY3K + NULL, /* nb_int */ + NULL, /* reserved */ +#else NULL, /* nb_coerce */ NULL, /* nb_int */ NULL, /* nb_long */ +#endif NULL, /* nb_float */ +#ifndef IS_PY3K NULL, /* nb_oct */ NULL /* nb_hex */ +#endif }; static PyMappingMethods typy_mapping = { @@ -1687,8 +1696,7 @@ static PyTypeObject type_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Type", /*tp_name*/ sizeof (type_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -1737,8 +1745,7 @@ static PyTypeObject field_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Field", /*tp_name*/ sizeof (field_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -1779,8 +1786,7 @@ }; static PyTypeObject type_iterator_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.TypeIterator", /*tp_name*/ sizeof (typy_iterator_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-utils.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-utils.c,v retrieving revision 1.13 diff -u -r1.13 py-utils.c --- gdb/python/py-utils.c 1 Mar 2012 21:06:54 -0000 1.13 +++ gdb/python/py-utils.c 14 Nov 2012 15:57:17 -0000 @@ -54,7 +54,8 @@ As an added bonus, the functions accepts a unicode string and returns it right away, so callers don't need to check which kind of string they've - got. + got. In Python 3, all strings are Unicode so this case is always the + one that applies. If the given object is not one of the mentioned string types, NULL is returned, with the TypeError python exception set. */ @@ -70,9 +71,10 @@ unicode_str = obj; Py_INCREF (obj); } - +#ifndef IS_PY3K else if (PyString_Check (obj)) unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL); +#endif else { PyErr_SetString (PyExc_TypeError, @@ -99,7 +101,11 @@ if (string == NULL) return NULL; +#ifdef IS_PY3K + result = xstrdup (PyBytes_AsString (string)); +#else result = xstrdup (PyString_AsString (string)); +#endif Py_DECREF (string); @@ -113,14 +119,8 @@ static PyObject * unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset) { - PyObject *string; - /* Translate string to named charset. */ - string = PyUnicode_AsEncodedString (unicode_str, charset, NULL); - if (string == NULL) - return NULL; - - return string; + return PyUnicode_AsEncodedString (unicode_str, charset, NULL); } /* Returns a newly allocated string with the contents of the given unicode @@ -167,7 +167,9 @@ /* Converts a python string (8-bit or unicode) to a target string in the target's charset. Returns NULL on error, with a python exception - set. */ + set. + + In Python 3, the returned object is a "bytes" object (not a string). */ PyObject * python_string_to_target_python_string (PyObject *obj) { @@ -221,7 +223,11 @@ int gdbpy_is_string (PyObject *obj) { +#ifdef IS_PY3K + return PyUnicode_Check (obj); +#else return PyString_Check (obj) || PyUnicode_Check (obj); +#endif } /* Return the string representation of OBJ, i.e., str (obj). @@ -235,7 +241,11 @@ if (str_obj != NULL) { +#ifdef IS_PY3K + char *msg = python_string_to_host_string (str_obj); +#else char *msg = xstrdup (PyString_AsString (str_obj)); +#endif Py_DECREF (str_obj); return msg; @@ -335,6 +345,11 @@ PyObject * gdb_py_object_from_longest (LONGEST l) { +#ifdef IS_PY3K + if (sizeof (l) > sizeof (long)) + return PyLong_FromLongLong (l); + return PyLong_FromLong (l); +#else #ifdef HAVE_LONG_LONG /* Defined by Python. */ /* If we have 'long long', and the value overflows a 'long', use a Python Long; otherwise use a Python Int. */ @@ -343,6 +358,7 @@ return PyLong_FromLongLong (l); #endif return PyInt_FromLong (l); +#endif } /* Convert a ULONGEST to the appropriate Python object -- either an @@ -351,6 +367,11 @@ PyObject * gdb_py_object_from_ulongest (ULONGEST l) { +#ifdef IS_PY3K + if (sizeof (l) > sizeof (unsigned long)) + return PyLong_FromUnsignedLongLong (l); + return PyLong_FromUnsignedLong (l); +#else #ifdef HAVE_LONG_LONG /* Defined by Python. */ /* If we have 'long long', and the value overflows a 'long', use a Python Long; otherwise use a Python Int. */ @@ -362,6 +383,7 @@ return PyLong_FromUnsignedLong (l); return PyInt_FromLong (l); +#endif } /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts Index: gdb/python/py-value.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-value.c,v retrieving revision 1.36 diff -u -r1.36 py-value.c --- gdb/python/py-value.c 30 Mar 2012 20:05:55 -0000 1.36 +++ gdb/python/py-value.c 14 Nov 2012 15:57:17 -0000 @@ -106,7 +106,7 @@ Py_XDECREF (self->dynamic_type); - self->ob_type->tp_free (self); + obj->ob_type->tp_free (self); } /* Helper to push a Value object on the global list. */ @@ -1140,6 +1140,7 @@ || (ptr_ok && TYPE_CODE (type) == TYPE_CODE_PTR)); } +#ifndef IS_PY3K /* Implements conversion to int. */ static PyObject * valpy_int (PyObject *self) @@ -1161,6 +1162,7 @@ return gdb_py_object_from_longest (l); } +#endif /* Implements conversion to long. */ static PyObject * @@ -1335,9 +1337,14 @@ value = value_copy (((value_object *) result)->value); } else +#ifdef IS_PY3K + PyErr_Format (PyExc_TypeError, + _("Could not convert Python object: %S."), obj); +#else PyErr_Format (PyExc_TypeError, _("Could not convert Python object: %s."), PyString_AsString (PyObject_Str (obj))); +#endif } if (except.reason < 0) { @@ -1439,7 +1446,9 @@ valpy_add, valpy_subtract, valpy_multiply, +#ifndef IS_PY3K valpy_divide, +#endif valpy_remainder, NULL, /* nb_divmod */ valpy_power, /* nb_power */ @@ -1453,12 +1462,31 @@ valpy_and, /* nb_and */ valpy_xor, /* nb_xor */ valpy_or, /* nb_or */ +#ifdef IS_PY3K + valpy_long, /* nb_int */ + NULL, /* reserved */ +#else NULL, /* nb_coerce */ valpy_int, /* nb_int */ valpy_long, /* nb_long */ +#endif valpy_float, /* nb_float */ +#ifndef IS_PY3K NULL, /* nb_oct */ - NULL /* nb_hex */ + NULL, /* nb_hex */ +#endif + NULL, /* nb_inplace_add */ + NULL, /* nb_inplace_subtract */ + NULL, /* nb_inplace_multiply */ + NULL, /* nb_inplace_remainder */ + NULL, /* nb_inplace_power */ + NULL, /* nb_inplace_lshift */ + NULL, /* nb_inplace_rshift */ + NULL, /* nb_inplace_and */ + NULL, /* nb_inplace_xor */ + NULL, /* nb_inplace_or */ + NULL, /* nb_floor_divide */ + valpy_divide /* nb_true_divide */ }; static PyMappingMethods value_object_as_mapping = { @@ -1468,8 +1496,7 @@ }; PyTypeObject value_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Value", /*tp_name*/ sizeof (value_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/python-config.py =================================================================== RCS file: /cvs/src/src/gdb/python/python-config.py,v retrieving revision 1.3 diff -u -r1.3 python-config.py --- gdb/python/python-config.py 31 Jan 2011 04:42:08 -0000 1.3 +++ gdb/python/python-config.py 14 Nov 2012 15:57:17 -0000 @@ -10,8 +10,8 @@ 'ldflags', 'help'] def exit_with_usage(code=1): - print >>sys.stderr, "Usage: %s [%s]" % (sys.argv[0], - '|'.join('--'+opt for opt in valid_opts)) + sys.stderr.write ("Usage: %s [%s]\n" % (sys.argv[0], + '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: @@ -24,6 +24,7 @@ pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var +abiflags = getattr (sys, "abiflags", "") opt_flags = [flag for (flag, val) in opts] @@ -44,17 +45,17 @@ for opt in opt_flags: if opt == '--prefix': - print to_unix_path(sysconfig.PREFIX) + print (to_unix_path(sysconfig.PREFIX)) elif opt == '--exec-prefix': - print to_unix_path(sysconfig.EXEC_PREFIX) + print (to_unix_path(sysconfig.EXEC_PREFIX)) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) - print to_unix_path(' '.join(flags)) + print (to_unix_path(' '.join(flags))) elif opt in ('--libs', '--ldflags'): libs = [] @@ -62,7 +63,7 @@ libs.extend(getvar('LIBS').split()) if getvar('SYSLIBS') is not None: libs.extend(getvar('SYSLIBS').split()) - libs.append('-lpython'+pyver) + libs.append('-lpython'+pyver + abiflags) # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': @@ -73,5 +74,5 @@ libs.insert(0, '-L' + sysconfig.PREFIX + '/libs') if getvar('LINKFORSHARED') is not None: libs.extend(getvar('LINKFORSHARED').split()) - print to_unix_path(' '.join(libs)) + print (to_unix_path(' '.join(libs))) Index: gdb/python/python-internal.h =================================================================== RCS file: /cvs/src/src/gdb/python/python-internal.h,v retrieving revision 1.59 diff -u -r1.59 python-internal.h --- gdb/python/python-internal.h 13 Sep 2012 21:49:31 -0000 1.59 +++ gdb/python/python-internal.h 14 Nov 2012 15:57:17 -0000 @@ -49,6 +49,25 @@ from including our python/python.h header file. */ #include <Python.h> #include <frameobject.h> + +#if PY_MAJOR_VERSION >= 3 +#define IS_PY3K 1 +#endif + +#ifdef IS_PY3K +#define Py_TPFLAGS_HAVE_ITER 0 +#define Py_TPFLAGS_CHECKTYPES 0 + +#define PyInt_Check PyLong_Check +#define PyInt_FromLong PyLong_FromLong +#define PyInt_AsLong PyLong_AsLong + +#define PyString_FromString PyUnicode_FromString +#define PyString_Decode PyUnicode_Decode +#define PyString_FromFormat PyUnicode_FromFormat +#define PyString_Check PyUnicode_Check +#endif + #if HAVE_LIBPYTHON2_4 /* Py_ssize_t is not defined until 2.5. Logical type for Py_ssize_t is Py_intptr_t, but that fails in 64-bit @@ -57,6 +76,18 @@ typedef int Py_ssize_t; #endif +#ifndef PyVarObject_HEAD_INIT +/* Python 2.4 does not define PyVarObject_HEAD_INIT. */ +#define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + +#endif + +#ifndef Py_TYPE +/* Python 2.4 does not define Py_TYPE. */ +#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#endif + /* If Python.h does not define WITH_THREAD, then the various GIL-related functions will not be defined. However, PyGILState_STATE will be. */ Index: gdb/python/python.c =================================================================== RCS file: /cvs/src/src/gdb/python/python.c,v retrieving revision 1.101 diff -u -r1.101 python.c --- gdb/python/python.c 12 Nov 2012 19:24:14 -0000 1.101 +++ gdb/python/python.c 14 Nov 2012 15:57:17 -0000 @@ -70,9 +70,14 @@ #include "gdbthread.h" #include "observer.h" #include "interps.h" +#include "event-top.h" static PyMethodDef GdbMethods[]; +#ifdef IS_PY3K +static struct PyModuleDef GdbModuleDef; +#endif + PyObject *gdb_module; PyObject *gdb_python_module; @@ -198,8 +203,10 @@ return -1; Py_DECREF (v); +#ifndef IS_PY3K if (Py_FlushLine ()) PyErr_Clear (); +#endif return 0; } @@ -1426,11 +1433,21 @@ /* Provide a prototype to silence -Wmissing-prototypes. */ extern initialize_file_ftype _initialize_python; +/* FIXME: there are a lot of calls below that do not check the return + value for errors. */ void _initialize_python (void) { char *cmd_name; struct cmd_list_element *cmd; + char *progname; +#ifdef IS_PY3K + int i; + size_t progsize, count; + char *oldloc; + wchar_t *progname_copy; +#endif + int python_init_ok = 0; add_com ("python-interactive", class_obscure, python_interactive_command, @@ -1510,14 +1527,46 @@ /foo/bin/python /foo/lib/pythonX.Y/... This must be done before calling Py_Initialize. */ - Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin", - SLASH_STRING, "python", NULL)); + progname = concat (ldirname (python_libdir), SLASH_STRING, "bin", + SLASH_STRING, "python", NULL); +#ifdef IS_PY3K + oldloc = setlocale (LC_ALL, NULL); + setlocale (LC_ALL, ""); + progsize = strlen (progname); + if (progsize == (size_t) -1) + { + fprintf (stderr, "Could not convert python path to string\n"); + return; + } + progname_copy = PyMem_Malloc ((progsize + 1) * sizeof (wchar_t)); + if (!progname_copy) + { + fprintf (stderr, "out of memory\n"); + return; + } + count = mbstowcs (progname_copy, progname, progsize + 1); + if (count == (size_t) -1) + { + fprintf (stderr, "Could not convert python path to string\n"); + return; + } + setlocale (LC_ALL, oldloc); + Py_SetProgramName (progname_copy); +#else + Py_SetProgramName (progname); +#endif #endif Py_Initialize (); PyEval_InitThreads (); +#ifdef IS_PY3K + gdb_module = PyModule_Create (&GdbModuleDef); + /* Add _gdb module to the list of known built-in modules. */ + _PyImport_FixupBuiltin (gdb_module, "_gdb"); +#else gdb_module = Py_InitModule ("_gdb", GdbMethods); +#endif /* The casts to (char*) are for python 2.4. */ PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version); @@ -1612,7 +1661,17 @@ sys_path = PySys_GetObject ("path"); - if (sys_path && PyList_Check (sys_path)) + /* If sys.path is not defined yet, define it first. */ + if (!(sys_path && PyList_Check (sys_path))) + { +#ifdef IS_PY3K + PySys_SetPath (L""); +#else + PySys_SetPath (""); +#endif + sys_path = PySys_GetObject ("path"); + } + if (sys_path && PyList_Check (sys_path)) { PyObject *pythondir; int err; @@ -1628,7 +1687,7 @@ Py_DECREF (pythondir); } else - PySys_SetPath (gdb_pythondir); + goto fail; /* Import the gdb module to finish the initialization, and add it to __main__ for convenience. */ @@ -1768,4 +1827,18 @@ {NULL, NULL, 0, NULL} }; +#ifdef IS_PY3K +static struct PyModuleDef GdbModuleDef = +{ + PyModuleDef_HEAD_INIT, + "_gdb", + NULL, + -1, + GdbMethods, + NULL, + NULL, + NULL, + NULL +}; +#endif #endif /* HAVE_PYTHON */ Index: gdb/python/lib/gdb/__init__.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/__init__.py,v retrieving revision 1.7 diff -u -r1.7 __init__.py --- gdb/python/lib/gdb/__init__.py 12 Nov 2012 17:41:57 -0000 1.7 +++ gdb/python/lib/gdb/__init__.py 14 Nov 2012 15:57:17 -0000 @@ -18,9 +18,17 @@ import sys import _gdb +if sys.version_info[0] > 2: + # Python 3 moved "reload" + from imp import reload + from _gdb import * -class GdbOutputFile: +class _GdbFile (object): + # These two are needed in Python 3 + encoding = "UTF-8" + errors = "strict" + def close(self): # Do nothing. return None @@ -28,9 +36,6 @@ def isatty(self): return False - def write(self, s): - write(s, stream=STDOUT) - def writelines(self, iterable): for line in iterable: self.write(line) @@ -38,26 +43,16 @@ def flush(self): flush() -sys.stdout = GdbOutputFile() - -class GdbOutputErrorFile: - def close(self): - # Do nothing. - return None +class GdbOutputFile (_GdbFile): + def write(self, s): + write(s, stream=STDOUT) - def isatty(self): - return False +sys.stdout = GdbOutputFile() +class GdbOutputErrorFile (_GdbFile): def write(self, s): write(s, stream=STDERR) - def writelines(self, iterable): - for line in iterable: - self.write(line) - - def flush(self): - flush() - sys.stderr = GdbOutputErrorFile() # Default prompt hook does nothing. @@ -107,7 +102,7 @@ else: __import__(modname) except: - print >> sys.stderr, traceback.format_exc() + sys.stderr.write (traceback.format_exc() + "\n") auto_load_packages() Index: gdb/python/lib/gdb/printing.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/printing.py,v retrieving revision 1.9 diff -u -r1.9 printing.py --- gdb/python/lib/gdb/printing.py 18 Apr 2012 06:46:46 -0000 1.9 +++ gdb/python/lib/gdb/printing.py 14 Nov 2012 15:57:17 -0000 @@ -19,7 +19,12 @@ import gdb import gdb.types import re +import sys +if sys.version_info[0] > 2: + # Python 3 removed basestring and long + basestring = str + long = int class PrettyPrinter(object): """A basic pretty-printer. Index: gdb/python/lib/gdb/prompt.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/prompt.py,v retrieving revision 1.2 diff -u -r1.2 prompt.py --- gdb/python/lib/gdb/prompt.py 4 Jan 2012 08:17:24 -0000 1.2 +++ gdb/python/lib/gdb/prompt.py 14 Nov 2012 15:57:17 -0000 @@ -98,8 +98,7 @@ functions.""" result = '' - keys = prompt_substitutions.keys() - keys.sort() + keys = sorted (prompt_substitutions.keys()) for key in keys: result += ' \\%s\t%s\n' % (key, prompt_substitutions[key].__doc__) result += """ Index: gdb/python/lib/gdb/command/explore.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/command/explore.py,v retrieving revision 1.1 diff -u -r1.1 explore.py --- gdb/python/lib/gdb/command/explore.py 11 Apr 2012 05:50:44 -0000 1.1 +++ gdb/python/lib/gdb/command/explore.py 14 Nov 2012 15:57:17 -0000 @@ -17,7 +17,12 @@ """Implementation of the GDB 'explore' command using the GDB Python API.""" import gdb +import sys +if sys.version_info[0] > 2: + # Python 3 renamed raw_input to input + raw_input = input + class Explorer(object): """Internal class which invokes other explorers.""" @@ -155,7 +160,7 @@ """A utility function which prints that the current exploration session is returning to the parent value. Useful when exploring values. """ - print "\nReturning to parent value...\n" + print ("\nReturning to parent value...\n") @staticmethod def return_to_parent_value_prompt(): @@ -170,7 +175,7 @@ """A utility function which prints that the current exploration session is returning to the enclosing type. Useful when exploring types. """ - print "\nReturning to enclosing type...\n" + print ("\nReturning to enclosing type...\n") @staticmethod def return_to_enclosing_type_prompt(): @@ -192,7 +197,7 @@ """ print ("'%s' is a scalar value of type '%s'." % (expr, value.type)) - print "%s = %s" % (expr, str(value)) + print ("%s = %s" % (expr, str(value))) if is_child: Explorer.return_to_parent_value_prompt() @@ -211,13 +216,13 @@ print ("%s is of an enumerated type '%s'." % (name, str(datatype))) else: - print "'%s' is an enumerated type." % name + print ("'%s' is an enumerated type." % name) else: if is_child: print ("%s is of a scalar type '%s'." % (name, str(datatype))) else: - print "'%s' is a scalar type." % name + print ("'%s' is a scalar type." % name) if is_child: Explorer.return_to_enclosing_type_prompt() @@ -268,7 +273,7 @@ try: str(element) except gdb.MemoryError: - print "Cannot read value at index %d." % index + print ("Cannot read value at index %d." % index) continue Explorer.explore_expr(element_expr, element, True) return False @@ -338,7 +343,7 @@ element = value[index] str(element) except gdb.MemoryError: - print "Cannot read value at index %d." % index + print ("Cannot read value at index %d." % index) raw_input("Press enter to continue... ") return True @@ -352,7 +357,7 @@ See Explorer.explore_type for more information. """ target_type = datatype.target() - print "%s is an array of '%s'." % (name, str(target_type)) + print ("%s is an array of '%s'." % (name, str(target_type))) Explorer.explore_type("the array element of %s" % name, target_type, is_child) @@ -371,9 +376,8 @@ if max_field_name_length < len(pair[0]): max_field_name_length = len(pair[0]) - format_str = " {0:>%d} = {1}" % max_field_name_length for pair in print_list: - print format_str.format(pair[0], pair[1]) + print ("%*s = %s" % (max_field_name_length, pair[0], pair[1])) @staticmethod def _get_real_field_count(fields): @@ -447,7 +451,7 @@ print_list.append((field.name, literal_value)) CompoundExplorer._print_fields(print_list) - print "" + print ("") if has_explorable_fields: choice = raw_input("Enter the field number of choice: ") @@ -484,7 +488,7 @@ (name, type_desc, str(datatype))) Explorer.return_to_enclosing_type_prompt() else: - print "'%s' is a %s with no fields." % (name, type_desc) + print ("'%s' is a %s with no fields." % (name, type_desc)) return False if is_child: @@ -515,7 +519,7 @@ current_choice = current_choice + 1 CompoundExplorer._print_fields(print_list) - print "" + print ("") if len(choice_to_compound_field_map) > 0: choice = raw_input("Enter the field number of choice: ") @@ -741,7 +745,7 @@ value = ExploreUtils.get_value_from_str(arg_str) if value is not None: - print "'%s' is of type '%s'." % (arg_str, str(value.type)) + print ("'%s' is of type '%s'." % (arg_str, str(value.type))) Explorer.explore_type(str(value.type), value.type, False) raise gdb.GdbError(("'%s' is not a type or value in the current " Index: gdb/python/lib/gdb/command/pretty_printers.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/command/pretty_printers.py,v retrieving revision 1.7 diff -u -r1.7 pretty_printers.py --- gdb/python/lib/gdb/command/pretty_printers.py 4 Jan 2012 08:17:25 -0000 1.7 +++ gdb/python/lib/gdb/command/pretty_printers.py 14 Nov 2012 15:57:17 -0000 @@ -124,21 +124,17 @@ """Print a list of pretty-printers.""" # A potential enhancement is to provide an option to list printers in # "lookup order" (i.e. unsorted). - sorted_pretty_printers = copy.copy(pretty_printers) - sorted_pretty_printers.sort(lambda x, y: - cmp(self.printer_name(x), - self.printer_name(y))) + sorted_pretty_printers = sorted (copy.copy(pretty_printers), + key = self.printer_name) for printer in sorted_pretty_printers: name = self.printer_name(printer) enabled = self.enabled_string(printer) if name_re.match(name): - print " %s%s" % (name, enabled) + print (" %s%s" % (name, enabled)) if (hasattr(printer, "subprinters") and printer.subprinters is not None): - sorted_subprinters = copy.copy(printer.subprinters) - sorted_subprinters.sort(lambda x, y: - cmp(self.printer_name(x), - self.printer_name(y))) + sorted_subprinters = sorted (copy.copy(printer.subprinters), + key = self.printer_name) for subprinter in sorted_subprinters: if (not subname_re or subname_re.match(subprinter.name)): @@ -150,7 +146,7 @@ obj_name_to_match, object_re, name_re, subname_re): """Subroutine of invoke to simplify it.""" if printer_list and object_re.match(obj_name_to_match): - print title + print (title) self.list_pretty_printers(printer_list, name_re, subname_re) def invoke(self, arg, from_tty): @@ -219,7 +215,7 @@ We count subprinters individually. """ (enabled_count, total_count) = count_all_enabled_printers() - print "%d of %d printers enabled" % (enabled_count, total_count) + print ("%d of %d printers enabled" % (enabled_count, total_count)) def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag): @@ -301,7 +297,7 @@ state = "enabled" else: state = "disabled" - print "%d %s %s" % (total, pluralize("printer", total), state) + print ("%d %s %s" % (total, pluralize("printer", total), state)) # Print the total list of printers currently enabled/disabled. # This is to further assist the user in determining whether the result ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-14 16:03 ` Paul_Koning @ 2012-11-19 16:49 ` Tom Tromey 2012-12-11 20:22 ` Paul_Koning 0 siblings, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-11-19 16:49 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches >>>>> "Paul" == <Paul_Koning@Dell.com> writes: Paul> Here is an updated patch which I believe addresses all the comments. Thanks. Paul> Should I add a NEWS entry for the Python 3 support? Yes, that would be good. Paul> PyTypeObject breakpoint_object_type = Paul> { Paul> - PyObject_HEAD_INIT (NULL) Paul> - 0, /*ob_size*/ Paul> + PyVarObject_HEAD_INIT (NULL, 0) The new line has the wrong indentation. Paul> static PyTypeObject cmdpy_object_type = Paul> { Paul> - PyObject_HEAD_INIT (NULL) Paul> - 0, /*ob_size*/ Paul> + PyVarObject_HEAD_INIT (NULL, 0) Ditto. Paul> PyTypeObject event_object_type = Paul> { Paul> - PyObject_HEAD_INIT (NULL) Paul> - 0, /* ob_size */ Paul> + PyVarObject_HEAD_INIT (NULL, 0) Ditto. Paul> static PyTypeObject eventregistry_object_type = Paul> { Paul> - PyObject_HEAD_INIT (NULL) Paul> - 0, /* ob_size */ Paul> + PyVarObject_HEAD_INIT (NULL, 0) Ditto. Paul> + if (except.reason < 0) Paul> + PyBuffer_Release (&pybuf); Paul> GDB_PY_HANDLE_EXCEPTION (except); Paul> +#ifdef IS_PY3K Paul> + PyBuffer_Release (&pybuf); Paul> +#endif I think the first PyBuffer_Release also has to be conditional on IS_PY3K here. It seems like you could just always call it after the try-catch rather than checking except.reason. Paul> +#ifdef IS_PY3K Paul> +static int Blank line between these two. Paul> @@ -638,6 +698,10 @@ Paul> } Paul> GDB_PY_HANDLE_EXCEPTION (except); Paul> +#ifdef IS_PY3K Paul> + PyBuffer_Release (&pybuf); Paul> +#endif It seems like PyBuffer_Release must be called before GDB_PY_HANDLE_EXCEPTION here. Paul> +#ifdef IS_PY3K Paul> +static PyBufferProcs buffer_procs = { Blank line between these two, and I think "{" on its own line is generally preferred. Paul> +++ gdb/python/py-value.c 14 Nov 2012 15:57:17 -0000 Paul> @@ -106,7 +106,7 @@ Paul> Py_XDECREF (self->dynamic_type); Paul> - self->ob_type->tp_free (self); Paul> + obj->ob_type->tp_free (self); Paul> } Doesn't this need the new Py_TYPE macro? Paul> +/* FIXME: there are a lot of calls below that do not check the return Paul> + value for errors. */ Don't bother with the new FIXME. Paul> + int python_init_ok = 0; This seems to be unused. Paul> + progname_copy = PyMem_Malloc ((progsize + 1) * sizeof (wchar_t)); [...] Paul> + Py_SetProgramName (progname_copy); I think a comment here explaining why we never free progname_copy would be nice to have. thanks, Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-11-19 16:49 ` Tom Tromey @ 2012-12-11 20:22 ` Paul_Koning 2012-12-11 20:37 ` Eli Zaretskii 2012-12-11 21:24 ` Tom Tromey 0 siblings, 2 replies; 16+ messages in thread From: Paul_Koning @ 2012-12-11 20:22 UTC (permalink / raw) To: tromey; +Cc: gdb-patches One more update. This addresses the comments you made a couple of weeks ago. I also added a NEWS entry, and also made changes to recently added file type_printers.py analogous to the changes in pretty_printers.py. Ok to commit? paul 2012-12-11 Paul Koning <paul_koning@dell.com> Add support for Python 3. * NEWS: Mention Python 3 support. * varobj.c (value_get_print_value): Use python_string_to_target_string. * python/py-block.c: Use PyVarObject_HEAD_INIT in initialization of type objects. * python/py-breakpoint.c: Ditto. * python/py-cmd.c: Ditto. * python/py-event.c: Ditto. * python/py-event.h: Ditto. * python/py-evtregistry.c: Ditto. * python/py-finishbreakpoint.c: Ditto. * python/py-frame.c: Ditto. * python/py-function.c: Ditto. * python/py-infthread.c: Ditto. * python/py-lazy-string.c: Ditto. * python/py-progspace.c: Ditto. * /python/py-symbol.c: Ditto. * python/py-evts.c: (gdbpy_initialize_py_events): Add module initialization for Python 3. * python/py-inferior.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (infpy_read_memory): Return memoryview object if Python 3. (infpy_write_memory): Use "s*" operand parsing code for Python 3. (infpy_search_memory): Ditto. (get_buffer): New function for Python 3. * python/py-objfile.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (objfpy_dealloc): Use Py_TYPE to call tp_free. * python/py-param.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (get_attr): Use PyUnicode_CompareWithASCIIString if Python 3. (set_attr): Ditto. * python/py-prettyprint.c (print_string_repr): use PyBytes methods instead of PyString methods if Python 3. (print_children): Skip push_dummy_python_frame call if Python 3. * python/py-symtab.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (salpy_dealloc): Use Py_TYPE to call tp_free. * python/py-type.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (field_dealloc): Use Py_TYPE to call tp_free. (typy_dealloc): Ditto. (type_object_as_number): Adjust struct initializations for differences in layout for Python 2 vs. Python 3. * python/py-utils.c (python_string_to_unicode): Omit non-Unicode string case for Python 3. (unicode_to_encoded_python_string): Shorten code (no functional change). (python_string_to_target_python_string): Comment that in Python 3 returned value is a Python "bytes" type. (gdbpy_is_string): Omit non-Unicode string check in Python 3. (gdb_py_object_from_longest): Omit non-long integer case in Python 3. (gdb_py_object_from_ulongest): Ditto. * python/py-value.c: Use PyVarObject_HEAD_INIT in initialization of type objects. (valpy_dealloc): Use Py_TYPE to call tp_free. (valpy_int): Omit function if Python 3. (convert_value_from_python): Use "%S" format (Python object as a string) if Python 3. (value_object_as_number): Adjust struct initializations for differences in layout for Python 2 vs. Python 3. * python/python-config.py: Adjust syntax for Python 3 compatibility. Include "sys.abiflags" string as part of python library name, if that attribute exists (Python 3). * python/python-internal.h (IS_PY3): Define if Python 3. (Py_TPFLAGS_HAVE_ITER, Py_TPFLAGS_CHECKTYPES): Define with placeholder value if Python 3. (PyInt_Check, PyInt_FromLong, PyInt_AsLong, PyString_FromString, PyString_Decode, PyString_FromFormat, PyString_Check): Define as analogous Python 3 API function if Python 3. (PyVarObject_HEAD_INIT): Define if not already defined. (Py_TYPE): Ditto. * python/python.c (eval_python_command): Omit Py_FlushLine call if Python 3. Check return values of all Python API calls for error. Supply dummy "python" and "python-interactive" commands if Python initialization failed. (_initialize_python): Convert argc to wchar_t** if Python 3. Add module initialization for Python 3. (finish_python_initialization): Pass wchar_t * argument to PySys_SetPath if Python 3. * python/lib/gdb/__init__.py: Define "reload" if Python 3. (_GdbFile): New class for common output file behavior. (GdbOutFile): Subclass from _GdbFile. (GdbOutputErrorFile): Ditto. (auto_load_packages): Adjust syntax for Python 3 compatibility. * python/lib/gdb/printing.py: Define basestr and int if Python 3. * python/lib/gdb/prompt.py: Use sorted() function rather than sort() method. * python/lib/gdb/command/explore.py: Define raw_input if Python 3. Adjust syntax for Python 3 compatibility. * python/lib/gdb/command/pretty_printers.py: Use sorted() function rather than sort() method. Adjust syntax for Python 3 compatibility. * python/lib/gdb/command/type_printers.py: Ditto. * doc/gdb.texinfo (Inferior.read_memory): Mention that the return value is a memoryview object if Python 3. Index: gdb/NEWS =================================================================== RCS file: /cvs/src/src/gdb/NEWS,v retrieving revision 1.555 diff -u -r1.555 NEWS --- gdb/NEWS 26 Nov 2012 19:23:51 -0000 1.555 +++ gdb/NEWS 11 Dec 2012 19:47:25 -0000 @@ -26,6 +26,8 @@ ** Types can be pretty-printed via a Python API. + ** Python 3 is now supported (in addition to Python 2.4 or later) + * New Python-based convenience functions: ** $_memeq(buf1, buf2, length) Index: gdb/varobj.c =================================================================== RCS file: /cvs/src/src/gdb/varobj.c,v retrieving revision 1.201 diff -u -r1.201 varobj.c --- gdb/varobj.c 3 Dec 2012 19:59:14 -0000 1.201 +++ gdb/varobj.c 11 Dec 2012 19:47:25 -0000 @@ -2910,12 +2910,10 @@ string_print. Otherwise just return the extracted string as a value. */ - PyObject *py_str - = python_string_to_target_python_string (output); + char *s = python_string_to_target_string (output); - if (py_str) + if (s) { - char *s = PyString_AsString (py_str); char *hint; hint = gdbpy_get_display_hint (value_formatter); @@ -2926,10 +2924,10 @@ xfree (hint); } - len = PyString_Size (py_str); + len = strlen (s); thevalue = xmemdup (s, len + 1, len + 1); type = builtin_type (gdbarch)->builtin_char; - Py_DECREF (py_str); + xfree (s); if (!string_print) { Index: gdb/doc/gdb.texinfo =================================================================== RCS file: /cvs/src/src/gdb/doc/gdb.texinfo,v retrieving revision 1.1029 diff -u -r1.1029 gdb.texinfo --- gdb/doc/gdb.texinfo 29 Nov 2012 17:49:20 -0000 1.1029 +++ gdb/doc/gdb.texinfo 11 Dec 2012 19:47:27 -0000 @@ -24171,7 +24171,8 @@ Read @var{length} bytes of memory from the inferior, starting at @var{address}. Returns a buffer object, which behaves much like an array or a string. It can be modified and given to the -@code{Inferior.write_memory} function. +@code{Inferior.write_memory} function. In @code{Python} 3, the return +value is a @code{memoryview} object. @end defun @findex Inferior.write_memory Index: gdb/python/py-block.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-block.c,v retrieving revision 1.12 diff -u -r1.12 py-block.c --- gdb/python/py-block.c 10 May 2012 19:50:09 -0000 1.12 +++ gdb/python/py-block.c 11 Dec 2012 19:47:28 -0000 @@ -475,8 +475,7 @@ }; PyTypeObject block_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Block", /*tp_name*/ sizeof (block_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -516,8 +515,7 @@ }; static PyTypeObject block_syms_iterator_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.BlockIterator", /*tp_name*/ sizeof (block_syms_iterator_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-breakpoint.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-breakpoint.c,v retrieving revision 1.34 diff -u -r1.34 py-breakpoint.c --- gdb/python/py-breakpoint.c 14 May 2012 15:38:40 -0000 1.34 +++ gdb/python/py-breakpoint.c 11 Dec 2012 19:47:28 -0000 @@ -981,8 +981,7 @@ PyTypeObject breakpoint_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Breakpoint", /*tp_name*/ sizeof (breakpoint_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-cmd.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-cmd.c,v retrieving revision 1.21 diff -u -r1.21 py-cmd.c --- gdb/python/py-cmd.c 13 Jun 2012 15:47:16 -0000 1.21 +++ gdb/python/py-cmd.c 11 Dec 2012 19:47:28 -0000 @@ -607,8 +607,7 @@ static PyTypeObject cmdpy_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Command", /*tp_name*/ sizeof (cmdpy_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-event.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-event.c,v retrieving revision 1.5 diff -u -r1.5 py-event.c --- gdb/python/py-event.c 8 Nov 2012 19:38:43 -0000 1.5 +++ gdb/python/py-event.c 11 Dec 2012 19:47:28 -0000 @@ -24,7 +24,7 @@ evpy_dealloc (PyObject *self) { Py_XDECREF (((event_object *) self)->dict); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } PyObject * @@ -143,8 +143,7 @@ PyTypeObject event_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Event", /* tp_name */ sizeof (event_object), /* tp_basicsize */ 0, /* tp_itemsize */ Index: gdb/python/py-event.h =================================================================== RCS file: /cvs/src/src/gdb/python/py-event.h,v retrieving revision 1.6 diff -u -r1.6 py-event.h --- gdb/python/py-event.h 8 Nov 2012 19:38:43 -0000 1.6 +++ gdb/python/py-event.h 11 Dec 2012 19:47:28 -0000 @@ -48,8 +48,7 @@ \ qual PyTypeObject name##_event_object_type = \ { \ - PyObject_HEAD_INIT (NULL) \ - 0, /* ob_size */ \ + PyVarObject_HEAD_INIT (NULL, 0) \ py_path, /* tp_name */ \ sizeof (event_object), /* tp_basicsize */ \ 0, /* tp_itemsize */ \ Index: gdb/python/py-evtregistry.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-evtregistry.c,v retrieving revision 1.3 diff -u -r1.3 py-evtregistry.c --- gdb/python/py-evtregistry.c 4 Jan 2012 08:17:25 -0000 1.3 +++ gdb/python/py-evtregistry.c 11 Dec 2012 19:47:28 -0000 @@ -97,7 +97,7 @@ evregpy_dealloc (PyObject *self) { Py_XDECREF (((eventregistry_object *) self)->callbacks); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Initialize the Python event registry code. */ @@ -131,8 +131,7 @@ static PyTypeObject eventregistry_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.EventRegistry", /* tp_name */ sizeof (eventregistry_object), /* tp_basicsize */ 0, /* tp_itemsize */ Index: gdb/python/py-evts.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-evts.c,v retrieving revision 1.5 diff -u -r1.5 py-evts.c --- gdb/python/py-evts.c 8 Nov 2012 19:38:43 -0000 1.5 +++ gdb/python/py-evts.c 11 Dec 2012 19:47:28 -0000 @@ -20,6 +20,21 @@ #include "defs.h" #include "py-events.h" +#ifdef IS_PY3K +static struct PyModuleDef EventModuleDef = +{ + PyModuleDef_HEAD_INIT, + "gdb.events", + NULL, + -1, + NULL, + NULL, + NULL, + NULL, + NULL +}; +#endif + /* Initialize python events. */ static int @@ -45,7 +60,11 @@ void gdbpy_initialize_py_events (void) { +#ifdef IS_PY3K + gdb_py_events.module = PyModule_Create (&EventModuleDef); +#else gdb_py_events.module = Py_InitModule ("events", NULL); +#endif if (!gdb_py_events.module) goto fail; @@ -62,7 +81,9 @@ if (add_new_registry (&gdb_py_events.new_objfile, "new_objfile") < 0) goto fail; +#ifndef IS_PY3K Py_INCREF (gdb_py_events.module); +#endif if (PyModule_AddObject (gdb_module, "events", (PyObject *) gdb_py_events.module) < 0) Index: gdb/python/py-finishbreakpoint.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-finishbreakpoint.c,v retrieving revision 1.8 diff -u -r1.8 py-finishbreakpoint.c --- gdb/python/py-finishbreakpoint.c 9 Nov 2012 19:58:03 -0000 1.8 +++ gdb/python/py-finishbreakpoint.c 11 Dec 2012 19:47:28 -0000 @@ -425,8 +425,7 @@ static PyTypeObject finish_breakpoint_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.FinishBreakpoint", /*tp_name*/ sizeof (struct finish_breakpoint_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-frame.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-frame.c,v retrieving revision 1.26 diff -u -r1.26 py-frame.c --- gdb/python/py-frame.c 7 Feb 2012 19:47:15 -0000 1.26 +++ gdb/python/py-frame.c 11 Dec 2012 19:47:28 -0000 @@ -662,8 +662,7 @@ }; PyTypeObject frame_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Frame", /* tp_name */ sizeof (frame_object), /* tp_basicsize */ 0, /* tp_itemsize */ Index: gdb/python/py-function.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-function.c,v retrieving revision 1.12 diff -u -r1.12 py-function.c --- gdb/python/py-function.c 4 Jan 2012 08:17:25 -0000 1.12 +++ gdb/python/py-function.c 11 Dec 2012 19:47:28 -0000 @@ -208,8 +208,7 @@ static PyTypeObject fnpy_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Function", /*tp_name*/ sizeof (PyObject), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-inferior.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-inferior.c,v retrieving revision 1.26 diff -u -r1.26 py-inferior.c --- gdb/python/py-inferior.c 9 Nov 2012 19:58:03 -0000 1.26 +++ gdb/python/py-inferior.c 11 Dec 2012 19:47:28 -0000 @@ -454,9 +454,14 @@ membuf_obj->addr = addr; membuf_obj->length = length; +#ifdef IS_PY3K + result = PyMemoryView_FromObject ((PyObject *) membuf_obj); +#else result = PyBuffer_FromReadWriteObject ((PyObject *) membuf_obj, 0, Py_END_OF_BUFFER); +#endif Py_DECREF (membuf_obj); + return result; } @@ -476,12 +481,22 @@ PyObject *addr_obj, *length_obj = NULL; volatile struct gdb_exception except; static char *keywords[] = { "address", "buffer", "length", NULL }; +#ifdef IS_PY3K + Py_buffer pybuf; + if (! PyArg_ParseTupleAndKeywords (args, kw, "Os*|O", keywords, + &addr_obj, &pybuf, + &length_obj)) + return NULL; + buffer = pybuf.buf; + buf_len = pybuf.len; +#else if (! PyArg_ParseTupleAndKeywords (args, kw, "Os#|O", keywords, &addr_obj, &buffer, &buf_len, &length_obj)) return NULL; +#endif TRY_CATCH (except, RETURN_MASK_ALL) { @@ -500,8 +515,12 @@ } write_memory_with_notification (addr, buffer, length); } +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif GDB_PY_HANDLE_EXCEPTION (except); + if (error) return NULL; @@ -513,7 +532,7 @@ mbpy_dealloc (PyObject *self) { xfree (((membuf_object *) self)->buffer); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Return a description of the Membuf object. */ @@ -528,6 +547,24 @@ pulongest (membuf_obj->length)); } +#ifdef IS_PY3K + +static int +get_buffer (PyObject *self, Py_buffer *buf, int flags) +{ + membuf_object *membuf_obj = (membuf_object *) self; + int ret; + + ret = PyBuffer_FillInfo (buf, self, membuf_obj->buffer, + membuf_obj->length, 0, + PyBUF_CONTIG); + buf->format = "c"; + + return ret; +} + +#else + static Py_ssize_t get_read_buffer (PyObject *self, Py_ssize_t segment, void **ptrptr) { @@ -572,6 +609,8 @@ return ret; } +#endif /* IS_PY3K */ + /* Implementation of gdb.search_memory (address, length, pattern). ADDRESS is the address to start the search. LENGTH specifies the scope of the @@ -585,17 +624,41 @@ { CORE_ADDR start_addr, length; static char *keywords[] = { "address", "length", "pattern", NULL }; - PyObject *pattern, *start_addr_obj, *length_obj; + PyObject *start_addr_obj, *length_obj; volatile struct gdb_exception except; Py_ssize_t pattern_size; const void *buffer; CORE_ADDR found_addr; int found = 0; +#ifdef IS_PY3K + Py_buffer pybuf; - if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords, + if (! PyArg_ParseTupleAndKeywords (args, kw, "OOs*", keywords, &start_addr_obj, &length_obj, + &pybuf)) + return NULL; + + buffer = pybuf.buf; + pattern_size = pybuf.len; +#else + PyObject *pattern; + + if (! PyArg_ParseTupleAndKeywords (args, kw, "OOO", keywords, + &start_addr_obj, &length_obj, &pattern)) + return NULL; + + if (!PyObject_CheckReadBuffer (pattern)) + { + PyErr_SetString (PyExc_RuntimeError, + _("The pattern is not a Python buffer.")); + + return NULL; + } + + if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1) return NULL; +#endif if (get_addr_from_python (start_addr_obj, &start_addr) && get_addr_from_python (length_obj, &length)) @@ -604,6 +667,10 @@ { PyErr_SetString (PyExc_ValueError, _("Search range is empty.")); + +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif return NULL; } /* Watch for overflows. */ @@ -613,23 +680,15 @@ PyErr_SetString (PyExc_ValueError, _("The search range is too large.")); +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif return NULL; } } else return NULL; - if (!PyObject_CheckReadBuffer (pattern)) - { - PyErr_SetString (PyExc_RuntimeError, - _("The pattern is not a Python buffer.")); - - return NULL; - } - - if (PyObject_AsReadBuffer (pattern, &buffer, &pattern_size) == -1) - return NULL; - TRY_CATCH (except, RETURN_MASK_ALL) { found = target_search_memory (start_addr, length, @@ -638,6 +697,10 @@ } GDB_PY_HANDLE_EXCEPTION (except); +#ifdef IS_PY3K + PyBuffer_Release (&pybuf); +#endif + if (found) return PyLong_FromLong (found_addr); else @@ -777,8 +840,7 @@ static PyTypeObject inferior_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /* ob_size */ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Inferior", /* tp_name */ sizeof (inferior_object), /* tp_basicsize */ 0, /* tp_itemsize */ @@ -817,6 +879,15 @@ 0 /* tp_alloc */ }; +#ifdef IS_PY3K + +static PyBufferProcs buffer_procs = +{ + get_buffer +}; + +#else + /* Python doesn't provide a decent way to get compatibility here. */ #if HAVE_LIBPYTHON2_4 #define CHARBUFFERPROC_NAME getcharbufferproc @@ -832,10 +903,10 @@ Python 2.5. */ (CHARBUFFERPROC_NAME) get_char_buffer }; +#endif /* IS_PY3K */ static PyTypeObject membuf_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Membuf", /*tp_name*/ sizeof (membuf_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-infthread.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-infthread.c,v retrieving revision 1.7 diff -u -r1.7 py-infthread.c --- gdb/python/py-infthread.c 18 May 2012 21:02:52 -0000 1.7 +++ gdb/python/py-infthread.c 11 Dec 2012 19:47:28 -0000 @@ -59,7 +59,7 @@ thpy_dealloc (PyObject *self) { Py_DECREF (((thread_object *) self)->inf_obj); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } static PyObject * @@ -301,8 +301,7 @@ static PyTypeObject thread_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.InferiorThread", /*tp_name*/ sizeof (thread_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-lazy-string.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-lazy-string.c,v retrieving revision 1.12 diff -u -r1.12 py-lazy-string.c --- gdb/python/py-lazy-string.c 1 Mar 2012 21:06:54 -0000 1.12 +++ gdb/python/py-lazy-string.c 11 Dec 2012 19:47:28 -0000 @@ -216,8 +216,7 @@ }; static PyTypeObject lazy_string_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.LazyString", /*tp_name*/ sizeof (lazy_string_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-objfile.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-objfile.c,v retrieving revision 1.12 diff -u -r1.12 py-objfile.c --- gdb/python/py-objfile.c 12 Nov 2012 17:41:57 -0000 1.12 +++ gdb/python/py-objfile.c 11 Dec 2012 19:47:28 -0000 @@ -62,7 +62,7 @@ Py_XDECREF (self->printers); Py_XDECREF (self->type_printers); - self->ob_type->tp_free ((PyObject *) self); + Py_TYPE (self)->tp_free (self); } static PyObject * @@ -277,8 +277,7 @@ static PyTypeObject objfile_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Objfile", /*tp_name*/ sizeof (objfile_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-param.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-param.c,v retrieving revision 1.15 diff -u -r1.15 py-param.c --- gdb/python/py-param.c 4 Jan 2012 08:17:25 -0000 1.15 +++ gdb/python/py-param.c 11 Dec 2012 19:47:28 -0000 @@ -102,7 +102,11 @@ get_attr (PyObject *obj, PyObject *attr_name) { if (PyString_Check (attr_name) +#ifdef IS_PY3K + && ! PyUnicode_CompareWithASCIIString (attr_name, "value")) +#else && ! strcmp (PyString_AsString (attr_name), "value")) +#endif { parmpy_object *self = (parmpy_object *) obj; @@ -276,7 +280,11 @@ set_attr (PyObject *obj, PyObject *attr_name, PyObject *val) { if (PyString_Check (attr_name) +#ifdef IS_PY3K + && ! PyUnicode_CompareWithASCIIString (attr_name, "value")) +#else && ! strcmp (PyString_AsString (attr_name), "value")) +#endif { if (!val) { @@ -773,8 +781,7 @@ static PyTypeObject parmpy_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Parameter", /*tp_name*/ sizeof (parmpy_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-prettyprint.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-prettyprint.c,v retrieving revision 1.28 diff -u -r1.28 py-prettyprint.c --- gdb/python/py-prettyprint.c 13 Sep 2012 21:49:31 -0000 1.28 +++ gdb/python/py-prettyprint.c 11 Dec 2012 19:47:28 -0000 @@ -348,8 +348,13 @@ struct type *type; make_cleanup_py_decref (string); +#ifdef IS_PY3K + output = (gdb_byte *) PyBytes_AS_STRING (string); + length = PyBytes_GET_SIZE (string); +#else output = PyString_AsString (string); length = PyString_Size (string); +#endif type = builtin_type (gdbarch)->builtin_char; if (hint && !strcmp (hint, "string")) @@ -383,6 +388,7 @@ return result; } +#ifndef IS_PY3K static void py_restore_tstate (void *p) { @@ -458,6 +464,7 @@ make_cleanup (py_restore_tstate, frame->f_back); return (PyObject *) frame; } +#endif /* Helper for apply_val_pretty_printer that formats children of the printer, if any exist. If is_py_none is true, then nothing has @@ -471,7 +478,10 @@ { int is_map, is_array, done_flag, pretty; unsigned int i; - PyObject *children, *iter, *frame; + PyObject *children, *iter; +#ifndef IS_PY3K + PyObject *frame; +#endif struct cleanup *cleanups; if (! PyObject_HasAttr (printer, gdbpy_children_cst)) @@ -515,6 +525,7 @@ /* Manufacture a dummy Python frame to work around Python 2.4 bug, where it insists on having a non-NULL tstate->frame when a generator is called. */ +#ifndef IS_PY3K frame = push_dummy_python_frame (); if (!frame) { @@ -522,6 +533,7 @@ goto done; } make_cleanup_py_decref (frame); +#endif done_flag = 0; for (i = 0; i < options->print_max; ++i) Index: gdb/python/py-progspace.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-progspace.c,v retrieving revision 1.10 diff -u -r1.10 py-progspace.c --- gdb/python/py-progspace.c 12 Nov 2012 17:41:57 -0000 1.10 +++ gdb/python/py-progspace.c 11 Dec 2012 19:47:28 -0000 @@ -70,7 +70,7 @@ Py_XDECREF (ps_self->printers); Py_XDECREF (ps_self->type_printers); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } static PyObject * @@ -264,8 +264,7 @@ static PyTypeObject pspace_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Progspace", /*tp_name*/ sizeof (pspace_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-symbol.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-symbol.c,v retrieving revision 1.15 diff -u -r1.15 py-symbol.c --- gdb/python/py-symbol.c 15 Oct 2012 15:20:26 -0000 1.15 +++ gdb/python/py-symbol.c 11 Dec 2012 19:47:28 -0000 @@ -561,8 +561,7 @@ }; PyTypeObject symbol_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Symbol", /*tp_name*/ sizeof (symbol_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-symtab.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-symtab.c,v retrieving revision 1.12 diff -u -r1.12 py-symtab.c --- gdb/python/py-symtab.c 18 Oct 2012 20:14:45 -0000 1.12 +++ gdb/python/py-symtab.c 11 Dec 2012 19:47:28 -0000 @@ -307,7 +307,7 @@ Py_DECREF (self_sal->symtab); xfree (self_sal->sal); - self_sal->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Given a sal, and a sal_object that has previously been allocated @@ -539,8 +539,7 @@ }; static PyTypeObject symtab_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Symtab", /*tp_name*/ sizeof (symtab_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -590,8 +589,7 @@ }; static PyTypeObject sal_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Symtab_and_line", /*tp_name*/ sizeof (sal_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-type.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-type.c,v retrieving revision 1.44 diff -u -r1.44 py-type.c --- gdb/python/py-type.c 12 Nov 2012 17:26:21 -0000 1.44 +++ gdb/python/py-type.c 11 Dec 2012 19:47:28 -0000 @@ -123,7 +123,7 @@ field_object *f = (field_object *) obj; Py_XDECREF (f->dict); - f->ob_type->tp_free (obj); + Py_TYPE (obj)->tp_free (obj); } static PyObject * @@ -1262,7 +1262,7 @@ if (type->next) type->next->prev = type->prev; - type->ob_type->tp_free (type); + Py_TYPE (type)->tp_free (type); } /* Return number of fields ("length" of the field dictionary). */ @@ -1657,7 +1657,9 @@ NULL, /* nb_add */ NULL, /* nb_subtract */ NULL, /* nb_multiply */ +#ifndef IS_PY3K NULL, /* nb_divide */ +#endif NULL, /* nb_remainder */ NULL, /* nb_divmod */ NULL, /* nb_power */ @@ -1671,12 +1673,19 @@ NULL, /* nb_and */ NULL, /* nb_xor */ NULL, /* nb_or */ +#ifdef IS_PY3K + NULL, /* nb_int */ + NULL, /* reserved */ +#else NULL, /* nb_coerce */ NULL, /* nb_int */ NULL, /* nb_long */ +#endif NULL, /* nb_float */ +#ifndef IS_PY3K NULL, /* nb_oct */ NULL /* nb_hex */ +#endif }; static PyMappingMethods typy_mapping = { @@ -1687,8 +1696,7 @@ static PyTypeObject type_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Type", /*tp_name*/ sizeof (type_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -1737,8 +1745,7 @@ static PyTypeObject field_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Field", /*tp_name*/ sizeof (field_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ @@ -1779,8 +1786,7 @@ }; static PyTypeObject type_iterator_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.TypeIterator", /*tp_name*/ sizeof (typy_iterator_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/py-utils.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-utils.c,v retrieving revision 1.13 diff -u -r1.13 py-utils.c --- gdb/python/py-utils.c 1 Mar 2012 21:06:54 -0000 1.13 +++ gdb/python/py-utils.c 11 Dec 2012 19:47:28 -0000 @@ -54,7 +54,8 @@ As an added bonus, the functions accepts a unicode string and returns it right away, so callers don't need to check which kind of string they've - got. + got. In Python 3, all strings are Unicode so this case is always the + one that applies. If the given object is not one of the mentioned string types, NULL is returned, with the TypeError python exception set. */ @@ -70,9 +71,10 @@ unicode_str = obj; Py_INCREF (obj); } - +#ifndef IS_PY3K else if (PyString_Check (obj)) unicode_str = PyUnicode_FromEncodedObject (obj, host_charset (), NULL); +#endif else { PyErr_SetString (PyExc_TypeError, @@ -99,7 +101,11 @@ if (string == NULL) return NULL; +#ifdef IS_PY3K + result = xstrdup (PyBytes_AsString (string)); +#else result = xstrdup (PyString_AsString (string)); +#endif Py_DECREF (string); @@ -113,14 +119,8 @@ static PyObject * unicode_to_encoded_python_string (PyObject *unicode_str, const char *charset) { - PyObject *string; - /* Translate string to named charset. */ - string = PyUnicode_AsEncodedString (unicode_str, charset, NULL); - if (string == NULL) - return NULL; - - return string; + return PyUnicode_AsEncodedString (unicode_str, charset, NULL); } /* Returns a newly allocated string with the contents of the given unicode @@ -167,7 +167,9 @@ /* Converts a python string (8-bit or unicode) to a target string in the target's charset. Returns NULL on error, with a python exception - set. */ + set. + + In Python 3, the returned object is a "bytes" object (not a string). */ PyObject * python_string_to_target_python_string (PyObject *obj) { @@ -221,7 +223,11 @@ int gdbpy_is_string (PyObject *obj) { +#ifdef IS_PY3K + return PyUnicode_Check (obj); +#else return PyString_Check (obj) || PyUnicode_Check (obj); +#endif } /* Return the string representation of OBJ, i.e., str (obj). @@ -235,7 +241,11 @@ if (str_obj != NULL) { +#ifdef IS_PY3K + char *msg = python_string_to_host_string (str_obj); +#else char *msg = xstrdup (PyString_AsString (str_obj)); +#endif Py_DECREF (str_obj); return msg; @@ -335,6 +345,11 @@ PyObject * gdb_py_object_from_longest (LONGEST l) { +#ifdef IS_PY3K + if (sizeof (l) > sizeof (long)) + return PyLong_FromLongLong (l); + return PyLong_FromLong (l); +#else #ifdef HAVE_LONG_LONG /* Defined by Python. */ /* If we have 'long long', and the value overflows a 'long', use a Python Long; otherwise use a Python Int. */ @@ -343,6 +358,7 @@ return PyLong_FromLongLong (l); #endif return PyInt_FromLong (l); +#endif } /* Convert a ULONGEST to the appropriate Python object -- either an @@ -351,6 +367,11 @@ PyObject * gdb_py_object_from_ulongest (ULONGEST l) { +#ifdef IS_PY3K + if (sizeof (l) > sizeof (unsigned long)) + return PyLong_FromUnsignedLongLong (l); + return PyLong_FromUnsignedLong (l); +#else #ifdef HAVE_LONG_LONG /* Defined by Python. */ /* If we have 'long long', and the value overflows a 'long', use a Python Long; otherwise use a Python Int. */ @@ -362,6 +383,7 @@ return PyLong_FromUnsignedLong (l); return PyInt_FromLong (l); +#endif } /* Like PyInt_AsLong, but returns 0 on failure, 1 on success, and puts Index: gdb/python/py-value.c =================================================================== RCS file: /cvs/src/src/gdb/python/py-value.c,v retrieving revision 1.36 diff -u -r1.36 py-value.c --- gdb/python/py-value.c 30 Mar 2012 20:05:55 -0000 1.36 +++ gdb/python/py-value.c 11 Dec 2012 19:47:28 -0000 @@ -106,7 +106,7 @@ Py_XDECREF (self->dynamic_type); - self->ob_type->tp_free (self); + Py_TYPE (self)->tp_free (self); } /* Helper to push a Value object on the global list. */ @@ -1140,6 +1140,7 @@ || (ptr_ok && TYPE_CODE (type) == TYPE_CODE_PTR)); } +#ifndef IS_PY3K /* Implements conversion to int. */ static PyObject * valpy_int (PyObject *self) @@ -1161,6 +1162,7 @@ return gdb_py_object_from_longest (l); } +#endif /* Implements conversion to long. */ static PyObject * @@ -1335,9 +1337,14 @@ value = value_copy (((value_object *) result)->value); } else +#ifdef IS_PY3K + PyErr_Format (PyExc_TypeError, + _("Could not convert Python object: %S."), obj); +#else PyErr_Format (PyExc_TypeError, _("Could not convert Python object: %s."), PyString_AsString (PyObject_Str (obj))); +#endif } if (except.reason < 0) { @@ -1439,7 +1446,9 @@ valpy_add, valpy_subtract, valpy_multiply, +#ifndef IS_PY3K valpy_divide, +#endif valpy_remainder, NULL, /* nb_divmod */ valpy_power, /* nb_power */ @@ -1453,12 +1462,31 @@ valpy_and, /* nb_and */ valpy_xor, /* nb_xor */ valpy_or, /* nb_or */ +#ifdef IS_PY3K + valpy_long, /* nb_int */ + NULL, /* reserved */ +#else NULL, /* nb_coerce */ valpy_int, /* nb_int */ valpy_long, /* nb_long */ +#endif valpy_float, /* nb_float */ +#ifndef IS_PY3K NULL, /* nb_oct */ - NULL /* nb_hex */ + NULL, /* nb_hex */ +#endif + NULL, /* nb_inplace_add */ + NULL, /* nb_inplace_subtract */ + NULL, /* nb_inplace_multiply */ + NULL, /* nb_inplace_remainder */ + NULL, /* nb_inplace_power */ + NULL, /* nb_inplace_lshift */ + NULL, /* nb_inplace_rshift */ + NULL, /* nb_inplace_and */ + NULL, /* nb_inplace_xor */ + NULL, /* nb_inplace_or */ + NULL, /* nb_floor_divide */ + valpy_divide /* nb_true_divide */ }; static PyMappingMethods value_object_as_mapping = { @@ -1468,8 +1496,7 @@ }; PyTypeObject value_object_type = { - PyObject_HEAD_INIT (NULL) - 0, /*ob_size*/ + PyVarObject_HEAD_INIT (NULL, 0) "gdb.Value", /*tp_name*/ sizeof (value_object), /*tp_basicsize*/ 0, /*tp_itemsize*/ Index: gdb/python/python-config.py =================================================================== RCS file: /cvs/src/src/gdb/python/python-config.py,v retrieving revision 1.3 diff -u -r1.3 python-config.py --- gdb/python/python-config.py 31 Jan 2011 04:42:08 -0000 1.3 +++ gdb/python/python-config.py 11 Dec 2012 19:47:28 -0000 @@ -10,8 +10,8 @@ 'ldflags', 'help'] def exit_with_usage(code=1): - print >>sys.stderr, "Usage: %s [%s]" % (sys.argv[0], - '|'.join('--'+opt for opt in valid_opts)) + sys.stderr.write ("Usage: %s [%s]\n" % (sys.argv[0], + '|'.join('--'+opt for opt in valid_opts))) sys.exit(code) try: @@ -24,6 +24,7 @@ pyver = sysconfig.get_config_var('VERSION') getvar = sysconfig.get_config_var +abiflags = getattr (sys, "abiflags", "") opt_flags = [flag for (flag, val) in opts] @@ -44,17 +45,17 @@ for opt in opt_flags: if opt == '--prefix': - print to_unix_path(sysconfig.PREFIX) + print (to_unix_path(sysconfig.PREFIX)) elif opt == '--exec-prefix': - print to_unix_path(sysconfig.EXEC_PREFIX) + print (to_unix_path(sysconfig.EXEC_PREFIX)) elif opt in ('--includes', '--cflags'): flags = ['-I' + sysconfig.get_python_inc(), '-I' + sysconfig.get_python_inc(plat_specific=True)] if opt == '--cflags': flags.extend(getvar('CFLAGS').split()) - print to_unix_path(' '.join(flags)) + print (to_unix_path(' '.join(flags))) elif opt in ('--libs', '--ldflags'): libs = [] @@ -62,7 +63,7 @@ libs.extend(getvar('LIBS').split()) if getvar('SYSLIBS') is not None: libs.extend(getvar('SYSLIBS').split()) - libs.append('-lpython'+pyver) + libs.append('-lpython'+pyver + abiflags) # add the prefix/lib/pythonX.Y/config dir, but only if there is no # shared library in prefix/lib/. if opt == '--ldflags': @@ -73,5 +74,5 @@ libs.insert(0, '-L' + sysconfig.PREFIX + '/libs') if getvar('LINKFORSHARED') is not None: libs.extend(getvar('LINKFORSHARED').split()) - print to_unix_path(' '.join(libs)) + print (to_unix_path(' '.join(libs))) Index: gdb/python/python-internal.h =================================================================== RCS file: /cvs/src/src/gdb/python/python-internal.h,v retrieving revision 1.59 diff -u -r1.59 python-internal.h --- gdb/python/python-internal.h 13 Sep 2012 21:49:31 -0000 1.59 +++ gdb/python/python-internal.h 11 Dec 2012 19:47:28 -0000 @@ -49,6 +49,25 @@ from including our python/python.h header file. */ #include <Python.h> #include <frameobject.h> + +#if PY_MAJOR_VERSION >= 3 +#define IS_PY3K 1 +#endif + +#ifdef IS_PY3K +#define Py_TPFLAGS_HAVE_ITER 0 +#define Py_TPFLAGS_CHECKTYPES 0 + +#define PyInt_Check PyLong_Check +#define PyInt_FromLong PyLong_FromLong +#define PyInt_AsLong PyLong_AsLong + +#define PyString_FromString PyUnicode_FromString +#define PyString_Decode PyUnicode_Decode +#define PyString_FromFormat PyUnicode_FromFormat +#define PyString_Check PyUnicode_Check +#endif + #if HAVE_LIBPYTHON2_4 /* Py_ssize_t is not defined until 2.5. Logical type for Py_ssize_t is Py_intptr_t, but that fails in 64-bit @@ -57,6 +76,18 @@ typedef int Py_ssize_t; #endif +#ifndef PyVarObject_HEAD_INIT +/* Python 2.4 does not define PyVarObject_HEAD_INIT. */ +#define PyVarObject_HEAD_INIT(type, size) \ + PyObject_HEAD_INIT(type) size, + +#endif + +#ifndef Py_TYPE +/* Python 2.4 does not define Py_TYPE. */ +#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type) +#endif + /* If Python.h does not define WITH_THREAD, then the various GIL-related functions will not be defined. However, PyGILState_STATE will be. */ Index: gdb/python/python.c =================================================================== RCS file: /cvs/src/src/gdb/python/python.c,v retrieving revision 1.102 diff -u -r1.102 python.c --- gdb/python/python.c 29 Nov 2012 19:11:48 -0000 1.102 +++ gdb/python/python.c 11 Dec 2012 19:47:28 -0000 @@ -70,9 +70,14 @@ #include "gdbthread.h" #include "observer.h" #include "interps.h" +#include "event-top.h" static PyMethodDef GdbMethods[]; +#ifdef IS_PY3K +static struct PyModuleDef GdbModuleDef; +#endif + PyObject *gdb_module; PyObject *gdb_python_module; @@ -198,8 +203,10 @@ return -1; Py_DECREF (v); +#ifndef IS_PY3K if (Py_FlushLine ()) PyErr_Clear (); +#endif return 0; } @@ -1431,6 +1438,13 @@ { char *cmd_name; struct cmd_list_element *cmd; + char *progname; +#ifdef IS_PY3K + int i; + size_t progsize, count; + char *oldloc; + wchar_t *progname_copy; +#endif add_com ("python-interactive", class_obscure, python_interactive_command, @@ -1510,14 +1524,50 @@ /foo/bin/python /foo/lib/pythonX.Y/... This must be done before calling Py_Initialize. */ - Py_SetProgramName (concat (ldirname (python_libdir), SLASH_STRING, "bin", - SLASH_STRING, "python", NULL)); + progname = concat (ldirname (python_libdir), SLASH_STRING, "bin", + SLASH_STRING, "python", NULL); +#ifdef IS_PY3K + oldloc = setlocale (LC_ALL, NULL); + setlocale (LC_ALL, ""); + progsize = strlen (progname); + if (progsize == (size_t) -1) + { + fprintf (stderr, "Could not convert python path to string\n"); + return; + } + progname_copy = PyMem_Malloc ((progsize + 1) * sizeof (wchar_t)); + if (!progname_copy) + { + fprintf (stderr, "out of memory\n"); + return; + } + count = mbstowcs (progname_copy, progname, progsize + 1); + if (count == (size_t) -1) + { + fprintf (stderr, "Could not convert python path to string\n"); + return; + } + setlocale (LC_ALL, oldloc); + + /* Note that Py_SetProgramName expects the string it is passed to + remain alive for the duration of the program's execution, so + it is not freed after this call. */ + Py_SetProgramName (progname_copy); +#else + Py_SetProgramName (progname); +#endif #endif Py_Initialize (); PyEval_InitThreads (); +#ifdef IS_PY3K + gdb_module = PyModule_Create (&GdbModuleDef); + /* Add _gdb module to the list of known built-in modules. */ + _PyImport_FixupBuiltin (gdb_module, "_gdb"); +#else gdb_module = Py_InitModule ("_gdb", GdbMethods); +#endif /* The casts to (char*) are for python 2.4. */ PyModule_AddStringConstant (gdb_module, "VERSION", (char*) version); @@ -1612,7 +1662,17 @@ sys_path = PySys_GetObject ("path"); - if (sys_path && PyList_Check (sys_path)) + /* If sys.path is not defined yet, define it first. */ + if (!(sys_path && PyList_Check (sys_path))) + { +#ifdef IS_PY3K + PySys_SetPath (L""); +#else + PySys_SetPath (""); +#endif + sys_path = PySys_GetObject ("path"); + } + if (sys_path && PyList_Check (sys_path)) { PyObject *pythondir; int err; @@ -1628,7 +1688,7 @@ Py_DECREF (pythondir); } else - PySys_SetPath (gdb_pythondir); + goto fail; /* Import the gdb module to finish the initialization, and add it to __main__ for convenience. */ @@ -1768,4 +1828,18 @@ {NULL, NULL, 0, NULL} }; +#ifdef IS_PY3K +static struct PyModuleDef GdbModuleDef = +{ + PyModuleDef_HEAD_INIT, + "_gdb", + NULL, + -1, + GdbMethods, + NULL, + NULL, + NULL, + NULL +}; +#endif #endif /* HAVE_PYTHON */ Index: gdb/python/lib/gdb/__init__.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/__init__.py,v retrieving revision 1.7 diff -u -r1.7 __init__.py --- gdb/python/lib/gdb/__init__.py 12 Nov 2012 17:41:57 -0000 1.7 +++ gdb/python/lib/gdb/__init__.py 11 Dec 2012 19:47:28 -0000 @@ -18,9 +18,17 @@ import sys import _gdb +if sys.version_info[0] > 2: + # Python 3 moved "reload" + from imp import reload + from _gdb import * -class GdbOutputFile: +class _GdbFile (object): + # These two are needed in Python 3 + encoding = "UTF-8" + errors = "strict" + def close(self): # Do nothing. return None @@ -28,9 +36,6 @@ def isatty(self): return False - def write(self, s): - write(s, stream=STDOUT) - def writelines(self, iterable): for line in iterable: self.write(line) @@ -38,26 +43,16 @@ def flush(self): flush() -sys.stdout = GdbOutputFile() - -class GdbOutputErrorFile: - def close(self): - # Do nothing. - return None +class GdbOutputFile (_GdbFile): + def write(self, s): + write(s, stream=STDOUT) - def isatty(self): - return False +sys.stdout = GdbOutputFile() +class GdbOutputErrorFile (_GdbFile): def write(self, s): write(s, stream=STDERR) - def writelines(self, iterable): - for line in iterable: - self.write(line) - - def flush(self): - flush() - sys.stderr = GdbOutputErrorFile() # Default prompt hook does nothing. @@ -107,7 +102,7 @@ else: __import__(modname) except: - print >> sys.stderr, traceback.format_exc() + sys.stderr.write (traceback.format_exc() + "\n") auto_load_packages() Index: gdb/python/lib/gdb/printing.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/printing.py,v retrieving revision 1.9 diff -u -r1.9 printing.py --- gdb/python/lib/gdb/printing.py 18 Apr 2012 06:46:46 -0000 1.9 +++ gdb/python/lib/gdb/printing.py 11 Dec 2012 19:47:28 -0000 @@ -19,7 +19,12 @@ import gdb import gdb.types import re +import sys +if sys.version_info[0] > 2: + # Python 3 removed basestring and long + basestring = str + long = int class PrettyPrinter(object): """A basic pretty-printer. Index: gdb/python/lib/gdb/prompt.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/prompt.py,v retrieving revision 1.2 diff -u -r1.2 prompt.py --- gdb/python/lib/gdb/prompt.py 4 Jan 2012 08:17:24 -0000 1.2 +++ gdb/python/lib/gdb/prompt.py 11 Dec 2012 19:47:28 -0000 @@ -98,8 +98,7 @@ functions.""" result = '' - keys = prompt_substitutions.keys() - keys.sort() + keys = sorted (prompt_substitutions.keys()) for key in keys: result += ' \\%s\t%s\n' % (key, prompt_substitutions[key].__doc__) result += """ Index: gdb/python/lib/gdb/command/explore.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/command/explore.py,v retrieving revision 1.1 diff -u -r1.1 explore.py --- gdb/python/lib/gdb/command/explore.py 11 Apr 2012 05:50:44 -0000 1.1 +++ gdb/python/lib/gdb/command/explore.py 11 Dec 2012 19:47:28 -0000 @@ -17,7 +17,12 @@ """Implementation of the GDB 'explore' command using the GDB Python API.""" import gdb +import sys +if sys.version_info[0] > 2: + # Python 3 renamed raw_input to input + raw_input = input + class Explorer(object): """Internal class which invokes other explorers.""" @@ -155,7 +160,7 @@ """A utility function which prints that the current exploration session is returning to the parent value. Useful when exploring values. """ - print "\nReturning to parent value...\n" + print ("\nReturning to parent value...\n") @staticmethod def return_to_parent_value_prompt(): @@ -170,7 +175,7 @@ """A utility function which prints that the current exploration session is returning to the enclosing type. Useful when exploring types. """ - print "\nReturning to enclosing type...\n" + print ("\nReturning to enclosing type...\n") @staticmethod def return_to_enclosing_type_prompt(): @@ -192,7 +197,7 @@ """ print ("'%s' is a scalar value of type '%s'." % (expr, value.type)) - print "%s = %s" % (expr, str(value)) + print ("%s = %s" % (expr, str(value))) if is_child: Explorer.return_to_parent_value_prompt() @@ -211,13 +216,13 @@ print ("%s is of an enumerated type '%s'." % (name, str(datatype))) else: - print "'%s' is an enumerated type." % name + print ("'%s' is an enumerated type." % name) else: if is_child: print ("%s is of a scalar type '%s'." % (name, str(datatype))) else: - print "'%s' is a scalar type." % name + print ("'%s' is a scalar type." % name) if is_child: Explorer.return_to_enclosing_type_prompt() @@ -268,7 +273,7 @@ try: str(element) except gdb.MemoryError: - print "Cannot read value at index %d." % index + print ("Cannot read value at index %d." % index) continue Explorer.explore_expr(element_expr, element, True) return False @@ -338,7 +343,7 @@ element = value[index] str(element) except gdb.MemoryError: - print "Cannot read value at index %d." % index + print ("Cannot read value at index %d." % index) raw_input("Press enter to continue... ") return True @@ -352,7 +357,7 @@ See Explorer.explore_type for more information. """ target_type = datatype.target() - print "%s is an array of '%s'." % (name, str(target_type)) + print ("%s is an array of '%s'." % (name, str(target_type))) Explorer.explore_type("the array element of %s" % name, target_type, is_child) @@ -371,9 +376,8 @@ if max_field_name_length < len(pair[0]): max_field_name_length = len(pair[0]) - format_str = " {0:>%d} = {1}" % max_field_name_length for pair in print_list: - print format_str.format(pair[0], pair[1]) + print (" %*s = %s" % (max_field_name_length, pair[0], pair[1])) @staticmethod def _get_real_field_count(fields): @@ -447,7 +451,7 @@ print_list.append((field.name, literal_value)) CompoundExplorer._print_fields(print_list) - print "" + print ("") if has_explorable_fields: choice = raw_input("Enter the field number of choice: ") @@ -484,7 +488,7 @@ (name, type_desc, str(datatype))) Explorer.return_to_enclosing_type_prompt() else: - print "'%s' is a %s with no fields." % (name, type_desc) + print ("'%s' is a %s with no fields." % (name, type_desc)) return False if is_child: @@ -515,7 +519,7 @@ current_choice = current_choice + 1 CompoundExplorer._print_fields(print_list) - print "" + print ("") if len(choice_to_compound_field_map) > 0: choice = raw_input("Enter the field number of choice: ") @@ -741,7 +745,7 @@ value = ExploreUtils.get_value_from_str(arg_str) if value is not None: - print "'%s' is of type '%s'." % (arg_str, str(value.type)) + print ("'%s' is of type '%s'." % (arg_str, str(value.type))) Explorer.explore_type(str(value.type), value.type, False) raise gdb.GdbError(("'%s' is not a type or value in the current " Index: gdb/python/lib/gdb/command/pretty_printers.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/command/pretty_printers.py,v retrieving revision 1.7 diff -u -r1.7 pretty_printers.py --- gdb/python/lib/gdb/command/pretty_printers.py 4 Jan 2012 08:17:25 -0000 1.7 +++ gdb/python/lib/gdb/command/pretty_printers.py 11 Dec 2012 19:47:28 -0000 @@ -124,21 +124,17 @@ """Print a list of pretty-printers.""" # A potential enhancement is to provide an option to list printers in # "lookup order" (i.e. unsorted). - sorted_pretty_printers = copy.copy(pretty_printers) - sorted_pretty_printers.sort(lambda x, y: - cmp(self.printer_name(x), - self.printer_name(y))) + sorted_pretty_printers = sorted (copy.copy(pretty_printers), + key = self.printer_name) for printer in sorted_pretty_printers: name = self.printer_name(printer) enabled = self.enabled_string(printer) if name_re.match(name): - print " %s%s" % (name, enabled) + print (" %s%s" % (name, enabled)) if (hasattr(printer, "subprinters") and printer.subprinters is not None): - sorted_subprinters = copy.copy(printer.subprinters) - sorted_subprinters.sort(lambda x, y: - cmp(self.printer_name(x), - self.printer_name(y))) + sorted_subprinters = sorted (copy.copy(printer.subprinters), + key = self.printer_name) for subprinter in sorted_subprinters: if (not subname_re or subname_re.match(subprinter.name)): @@ -150,7 +146,7 @@ obj_name_to_match, object_re, name_re, subname_re): """Subroutine of invoke to simplify it.""" if printer_list and object_re.match(obj_name_to_match): - print title + print (title) self.list_pretty_printers(printer_list, name_re, subname_re) def invoke(self, arg, from_tty): @@ -219,7 +215,7 @@ We count subprinters individually. """ (enabled_count, total_count) = count_all_enabled_printers() - print "%d of %d printers enabled" % (enabled_count, total_count) + print ("%d of %d printers enabled" % (enabled_count, total_count)) def do_enable_pretty_printer_1 (pretty_printers, name_re, subname_re, flag): @@ -301,7 +297,7 @@ state = "enabled" else: state = "disabled" - print "%d %s %s" % (total, pluralize("printer", total), state) + print ("%d %s %s" % (total, pluralize("printer", total), state)) # Print the total list of printers currently enabled/disabled. # This is to further assist the user in determining whether the result Index: gdb/python/lib/gdb/command/type_printers.py =================================================================== RCS file: /cvs/src/src/gdb/python/lib/gdb/command/type_printers.py,v retrieving revision 1.1 diff -u -r1.1 type_printers.py --- gdb/python/lib/gdb/command/type_printers.py 12 Nov 2012 17:41:58 -0000 1.1 +++ gdb/python/lib/gdb/command/type_printers.py 11 Dec 2012 19:47:28 -0000 @@ -33,29 +33,29 @@ """Print a list of type printers.""" # A potential enhancement is to provide an option to list printers in # "lookup order" (i.e. unsorted). - sorted_type_printers = copy.copy(type_printers) - sorted_type_printers.sort(lambda x, y: cmp(x.name, y.name)) + sorted_type_printers = sorted (copy.copy(type_printers), + key = lambda x: x.name) for printer in sorted_type_printers: if printer.enabled: enabled = '' else: enabled = " [disabled]" - print " %s%s" % (printer.name, enabled) + print (" %s%s" % (printer.name, enabled)) def invoke(self, arg, from_tty): """GDB calls this to perform the command.""" sep = '' for objfile in gdb.objfiles(): if objfile.type_printers: - print "%sType printers for %s:" % (sep, objfile.name) + print ("%sType printers for %s:" % (sep, objfile.name)) self.list_type_printers(objfile.type_printers) sep = '\n' if gdb.current_progspace().type_printers: - print "%sType printers for program space:" % sep + print ("%sType printers for program space:" % sep) self.list_type_printers(gdb.current_progspace().type_printers) sep = '\n' if gdb.type_printers: - print "%sGlobal type printers:" % sep + print ("%sGlobal type printers:" % sep) self.list_type_printers(gdb.type_printers) class _EnableOrDisableCommand(gdb.Command): @@ -83,7 +83,7 @@ if self.set_some(name, gdb.type_printers): ok = True if not ok: - print "No type printer named '%s'" % name + print ("No type printer named '%s'" % name) def add_some(self, result, word, printers): for p in printers: ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-12-11 20:22 ` Paul_Koning @ 2012-12-11 20:37 ` Eli Zaretskii 2012-12-11 21:24 ` Tom Tromey 1 sibling, 0 replies; 16+ messages in thread From: Eli Zaretskii @ 2012-12-11 20:37 UTC (permalink / raw) To: Paul_Koning; +Cc: tromey, gdb-patches > From: <Paul_Koning@Dell.com> > CC: <gdb-patches@sourceware.org> > Date: Tue, 11 Dec 2012 20:22:13 +0000 > > One more update. This addresses the comments you made a couple of weeks ago. I also added a NEWS entry, and also made changes to recently added file type_printers.py analogous to the changes in pretty_printers.py. > > Ok to commit? The documentation parts are okay, thanks. ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-12-11 20:22 ` Paul_Koning 2012-12-11 20:37 ` Eli Zaretskii @ 2012-12-11 21:24 ` Tom Tromey 2012-12-12 17:00 ` Paul_Koning 1 sibling, 1 reply; 16+ messages in thread From: Tom Tromey @ 2012-12-11 21:24 UTC (permalink / raw) To: Paul_Koning; +Cc: gdb-patches >>>>> "Paul" == <Paul_Koning@Dell.com> writes: Paul> One more update. This addresses the comments you made a couple of Paul> weeks ago. I also added a NEWS entry, and also made changes to Paul> recently added file type_printers.py analogous to the changes in Paul> pretty_printers.py. Ok to commit? Ok. Thanks for doing this. Tom ^ permalink raw reply [flat|nested] 16+ messages in thread
* Re: [PATCH] Python 3 support, part 1 (non-testsuite part) 2012-12-11 21:24 ` Tom Tromey @ 2012-12-12 17:00 ` Paul_Koning 0 siblings, 0 replies; 16+ messages in thread From: Paul_Koning @ 2012-12-12 17:00 UTC (permalink / raw) To: tromey; +Cc: gdb-patches On Dec 11, 2012, at 4:24 PM, Tom Tromey wrote: >>>>>> "Paul" == <Paul_Koning@Dell.com> writes: > > Paul> One more update. This addresses the comments you made a couple of > Paul> weeks ago. I also added a NEWS entry, and also made changes to > Paul> recently added file type_printers.py analogous to the changes in > Paul> pretty_printers.py. Ok to commit? > > Ok. Thanks for doing this. > > Tom Thanks. Committed. paul ^ permalink raw reply [flat|nested] 16+ messages in thread
end of thread, other threads:[~2012-12-12 17:00 UTC | newest] Thread overview: 16+ messages (download: mbox.gz / follow: Atom feed) -- links below jump to the message on this page -- 2012-11-12 16:06 [PATCH] Python 3 support, part 1 (non-testsuite part) Paul_Koning 2012-11-12 20:43 ` Tom Tromey 2012-11-12 21:37 ` Paul_Koning 2012-11-13 18:53 ` Tom Tromey 2012-11-13 19:02 ` Paul_Koning 2012-11-13 19:12 ` Tom Tromey 2012-11-13 19:26 ` Paul_Koning 2012-11-13 19:43 ` Tom Tromey 2012-11-13 19:56 ` Paul_Koning 2012-11-13 20:24 ` Tom Tromey 2012-11-14 16:03 ` Paul_Koning 2012-11-19 16:49 ` Tom Tromey 2012-12-11 20:22 ` Paul_Koning 2012-12-11 20:37 ` Eli Zaretskii 2012-12-11 21:24 ` Tom Tromey 2012-12-12 17:00 ` Paul_Koning
This is a public inbox, see mirroring instructions for how to clone and mirror all data and code used for this inbox