[Stackless-checkins] r51421 - in stackless/trunk: Doc/api/abstract.tex Doc/api/concrete.tex Doc/api/exceptions.tex Doc/api/init.tex Doc/commontex/boilerplate.tex Doc/dist/dist.tex Doc/howto/sockets.tex Doc/lib/libctypes.tex Doc/lib/libexcs.tex Doc/lib/libinspect.tex Doc/lib/liblinecache.tex Doc/lib/libturtle.tex Doc/lib/libunittest.tex Doc/lib/libwarnings.tex Doc/ref/ref2.tex Doc/ref/ref3.tex Doc/whatsnew/whatsnew25.tex Include/abstract.h Include/object.h Include/patchlevel.h Include/pyerrors.h Include/unicodeobject.h Lib/Cookie.py Lib/cgi.py Lib/compiler/ast.py Lib/compiler/pycodegen.py Lib/compiler/symbols.py Lib/ctypes/__init__.py Lib/ctypes/test/test_as_parameter.py Lib/ctypes/test/test_functions.py Lib/ctypes/test/test_numbers.py Lib/ctypes/test/test_prototypes.py Lib/ctypes/test/test_python_api.py Lib/distutils/__init__.py Lib/idlelib Lib/idlelib/Bindings.py Lib/idlelib/CREDITS.txt Lib/idlelib/CodeContext.py Lib/idlelib/EditorWindow.py Lib/idlelib/NEWS.txt Lib/idlelib/PyShell.py L! ib/idlelib/ScriptBinding.py Lib/idlelib/idlever.py Lib/logging/__init__.py Lib/logging/config.py Lib/site.py Lib/string.py Lib/tabnanny.py Lib/test/exception_hierarchy.txt Lib/test/inspect_fodder2.py Lib/test/output/test_cgi Lib/test/regrtest.py Lib/test/test_bigaddrspace.py Lib/test/test_builtin.py Lib/test/test_bz2.py Lib/test/test_cgi.py Lib/test/test_code.py Lib/test/test_compiler.py Lib/test/test_descr.py Lib/test/test_format.py Lib/test/test_index.py Lib/test/test_inspect.py Lib/test/test_logging.py Lib/test/test_mailbox.py Lib/test/test_shutil.py Lib/test/test_signal.py Lib/test/test_socketserver.py Lib/test/test_struct.py Lib/test/test_support.py Lib/test/test_threading.py Lib/test/test_threadsignals.py Lib/test/test_trace.py Lib/test/test_traceback.py Lib/test/test_types.py Lib/test/test_uuid.py Lib/test/test_xml_etree_c.py Lib/tokenize.py Lib/trace.py Lib/traceback.py Lib/uuid.py Lib/webbrowser.py Lib/xml/etree Misc/ACKS Misc/NEWS Misc/PURIFY.README Misc/README.kl! ocwork Misc/RPM/python-2.5.spec Modules/Setup.dist Modules/_bsddb.c Modules/_codecsmodule.c Modules/_ctypes/_ctypes.c Modules/_ctypes/_ctypes_test.c Modules/_ctypes/callbacks.c Modules/_ctypes/callproc.c Modules/_ctypes/cfield.c Modules/_ctypes/ctypes.h Modules/_ctypes/libffi/configure Modules/_ctypes/libffi/configure.ac Mod

richard.tew python-checkins at python.org
Mon Aug 21 11:10:27 CEST 2006


Author: richard.tew
Date: Mon Aug 21 11:10:05 2006
New Revision: 51421

Added:
   stackless/trunk/Lib/ctypes/test/test_as_parameter.py
      - copied unchanged from r51332, python/trunk/Lib/ctypes/test/test_as_parameter.py
   stackless/trunk/Lib/test/test_bigaddrspace.py
      - copied unchanged from r51332, python/trunk/Lib/test/test_bigaddrspace.py
Modified:
   stackless/trunk/Doc/api/abstract.tex
   stackless/trunk/Doc/api/concrete.tex
   stackless/trunk/Doc/api/exceptions.tex
   stackless/trunk/Doc/api/init.tex
   stackless/trunk/Doc/commontex/boilerplate.tex
   stackless/trunk/Doc/dist/dist.tex
   stackless/trunk/Doc/howto/sockets.tex
   stackless/trunk/Doc/lib/libctypes.tex
   stackless/trunk/Doc/lib/libexcs.tex
   stackless/trunk/Doc/lib/libinspect.tex
   stackless/trunk/Doc/lib/liblinecache.tex
   stackless/trunk/Doc/lib/libturtle.tex
   stackless/trunk/Doc/lib/libunittest.tex
   stackless/trunk/Doc/lib/libwarnings.tex
   stackless/trunk/Doc/ref/ref2.tex
   stackless/trunk/Doc/ref/ref3.tex
   stackless/trunk/Doc/whatsnew/whatsnew25.tex
   stackless/trunk/Include/abstract.h
   stackless/trunk/Include/object.h
   stackless/trunk/Include/patchlevel.h
   stackless/trunk/Include/pyerrors.h
   stackless/trunk/Include/unicodeobject.h
   stackless/trunk/Lib/Cookie.py
   stackless/trunk/Lib/cgi.py
   stackless/trunk/Lib/compiler/ast.py
   stackless/trunk/Lib/compiler/pycodegen.py
   stackless/trunk/Lib/compiler/symbols.py
   stackless/trunk/Lib/ctypes/__init__.py
   stackless/trunk/Lib/ctypes/test/test_functions.py
   stackless/trunk/Lib/ctypes/test/test_numbers.py
   stackless/trunk/Lib/ctypes/test/test_prototypes.py
   stackless/trunk/Lib/ctypes/test/test_python_api.py
   stackless/trunk/Lib/distutils/__init__.py
   stackless/trunk/Lib/idlelib/   (props changed)
   stackless/trunk/Lib/idlelib/Bindings.py
   stackless/trunk/Lib/idlelib/CREDITS.txt
   stackless/trunk/Lib/idlelib/CodeContext.py
   stackless/trunk/Lib/idlelib/EditorWindow.py
   stackless/trunk/Lib/idlelib/NEWS.txt
   stackless/trunk/Lib/idlelib/PyShell.py
   stackless/trunk/Lib/idlelib/ScriptBinding.py
   stackless/trunk/Lib/idlelib/idlever.py
   stackless/trunk/Lib/logging/__init__.py
   stackless/trunk/Lib/logging/config.py
   stackless/trunk/Lib/site.py
   stackless/trunk/Lib/string.py
   stackless/trunk/Lib/tabnanny.py
   stackless/trunk/Lib/test/exception_hierarchy.txt
   stackless/trunk/Lib/test/inspect_fodder2.py
   stackless/trunk/Lib/test/output/test_cgi
   stackless/trunk/Lib/test/regrtest.py
   stackless/trunk/Lib/test/test_builtin.py
   stackless/trunk/Lib/test/test_bz2.py
   stackless/trunk/Lib/test/test_cgi.py
   stackless/trunk/Lib/test/test_code.py
   stackless/trunk/Lib/test/test_compiler.py
   stackless/trunk/Lib/test/test_descr.py
   stackless/trunk/Lib/test/test_format.py
   stackless/trunk/Lib/test/test_index.py
   stackless/trunk/Lib/test/test_inspect.py
   stackless/trunk/Lib/test/test_logging.py
   stackless/trunk/Lib/test/test_mailbox.py
   stackless/trunk/Lib/test/test_shutil.py
   stackless/trunk/Lib/test/test_signal.py
   stackless/trunk/Lib/test/test_socketserver.py
   stackless/trunk/Lib/test/test_struct.py
   stackless/trunk/Lib/test/test_support.py
   stackless/trunk/Lib/test/test_threading.py
   stackless/trunk/Lib/test/test_threadsignals.py
   stackless/trunk/Lib/test/test_trace.py
   stackless/trunk/Lib/test/test_traceback.py
   stackless/trunk/Lib/test/test_types.py
   stackless/trunk/Lib/test/test_uuid.py
   stackless/trunk/Lib/test/test_xml_etree_c.py
   stackless/trunk/Lib/tokenize.py
   stackless/trunk/Lib/trace.py
   stackless/trunk/Lib/traceback.py
   stackless/trunk/Lib/uuid.py
   stackless/trunk/Lib/webbrowser.py
   stackless/trunk/Lib/xml/etree/   (props changed)
   stackless/trunk/Misc/ACKS
   stackless/trunk/Misc/NEWS
   stackless/trunk/Misc/PURIFY.README
   stackless/trunk/Misc/README.klocwork
   stackless/trunk/Misc/RPM/python-2.5.spec
   stackless/trunk/Modules/Setup.dist
   stackless/trunk/Modules/_bsddb.c
   stackless/trunk/Modules/_codecsmodule.c
   stackless/trunk/Modules/_ctypes/_ctypes.c
   stackless/trunk/Modules/_ctypes/_ctypes_test.c
   stackless/trunk/Modules/_ctypes/callbacks.c
   stackless/trunk/Modules/_ctypes/callproc.c
   stackless/trunk/Modules/_ctypes/cfield.c
   stackless/trunk/Modules/_ctypes/ctypes.h
   stackless/trunk/Modules/_ctypes/libffi/configure
   stackless/trunk/Modules/_ctypes/libffi/configure.ac
   stackless/trunk/Modules/_ctypes/libffi/fficonfig.py.in
   stackless/trunk/Modules/_cursesmodule.c
   stackless/trunk/Modules/_elementtree.c
   stackless/trunk/Modules/_hotshot.c
   stackless/trunk/Modules/_sre.c
   stackless/trunk/Modules/_struct.c
   stackless/trunk/Modules/_testcapimodule.c
   stackless/trunk/Modules/_tkinter.c
   stackless/trunk/Modules/arraymodule.c
   stackless/trunk/Modules/bz2module.c
   stackless/trunk/Modules/collectionsmodule.c
   stackless/trunk/Modules/expat/xmlparse.c
   stackless/trunk/Modules/mmapmodule.c
   stackless/trunk/Modules/operator.c
   stackless/trunk/Modules/posixmodule.c
   stackless/trunk/Modules/rgbimgmodule.c
   stackless/trunk/Modules/socketmodule.c
   stackless/trunk/Modules/unicodedata.c
   stackless/trunk/Modules/zipimport.c
   stackless/trunk/Objects/abstract.c
   stackless/trunk/Objects/bufferobject.c
   stackless/trunk/Objects/classobject.c
   stackless/trunk/Objects/descrobject.c
   stackless/trunk/Objects/dictnotes.txt
   stackless/trunk/Objects/dictobject.c
   stackless/trunk/Objects/exceptions.c
   stackless/trunk/Objects/intobject.c
   stackless/trunk/Objects/listobject.c
   stackless/trunk/Objects/longobject.c
   stackless/trunk/Objects/object.c
   stackless/trunk/Objects/sliceobject.c
   stackless/trunk/Objects/stringobject.c
   stackless/trunk/Objects/structseq.c
   stackless/trunk/Objects/tupleobject.c
   stackless/trunk/Objects/typeobject.c
   stackless/trunk/Objects/unicodeobject.c
   stackless/trunk/PCbuild/_msi.vcproj
   stackless/trunk/PCbuild/_ssl.mak
   stackless/trunk/PCbuild/_ssl.vcproj
   stackless/trunk/PCbuild/build_ssl.py
   stackless/trunk/Parser/   (props changed)
   stackless/trunk/Parser/grammar.c
   stackless/trunk/Parser/parsetok.c
   stackless/trunk/Python/ast.c
   stackless/trunk/Python/bltinmodule.c
   stackless/trunk/Python/ceval.c
   stackless/trunk/Python/compile.c
   stackless/trunk/Python/errors.c
   stackless/trunk/Python/getargs.c
   stackless/trunk/Python/import.c
   stackless/trunk/Python/marshal.c
   stackless/trunk/Python/pystate.c
   stackless/trunk/Python/pythonrun.c
   stackless/trunk/Python/symtable.c
   stackless/trunk/README
   stackless/trunk/Tools/buildbot/   (props changed)
   stackless/trunk/Tools/msi/msi.py
   stackless/trunk/configure
   stackless/trunk/configure.in
   stackless/trunk/setup.py
Log:
Merged in the Python trunk changes from 2.5b3 (r51065) to 2.5c1 (r51332).  The Stackless trunk will continue to mirror the Python trunk, so it will be branched to a 'release25-maint' branch to match how core Python development is done.

Modified: stackless/trunk/Doc/api/abstract.tex
==============================================================================
--- stackless/trunk/Doc/api/abstract.tex	(original)
+++ stackless/trunk/Doc/api/abstract.tex	Mon Aug 21 11:10:05 2006
@@ -693,12 +693,31 @@
   \samp{float(\var{o})}.\bifuncindex{float}
 \end{cfuncdesc}
 
-\begin{cfuncdesc}{Py_ssize_t}{PyNumber_Index}{PyObject *o}
-  Returns the \var{o} converted to a Py_ssize_t integer on success, or
-  -1 with an exception raised on failure.
+\begin{cfuncdesc}{PyObject*}{PyNumber_Index}{PyObject *o}
+  Returns the \var{o} converted to a Python int or long on success or \NULL{}
+  with a TypeError exception raised on failure.
   \versionadded{2.5}
 \end{cfuncdesc}
 
+\begin{cfuncdesc}{Py_ssize_t}{PyNumber_AsSsize_t}{PyObject *o, PyObject *exc}
+  Returns \var{o} converted to a Py_ssize_t value if \var{o}
+  can be interpreted as an integer. If \var{o} can be converted to a Python
+  int or long but the attempt to convert to a Py_ssize_t value
+  would raise an \exception{OverflowError}, then the \var{exc} argument
+  is the type of exception that will be raised (usually \exception{IndexError}
+  or \exception{OverflowError}).  If \var{exc} is \NULL{}, then the exception
+  is cleared and the value is clipped to \var{PY_SSIZE_T_MIN}
+  for a negative integer or \var{PY_SSIZE_T_MAX} for a positive integer.
+  \versionadded{2.5}
+\end{cfuncdesc}
+
+\begin{cfuncdesc}{int}{PyIndex_Check}{PyObject *o}
+  Returns True if \var{o} is an index integer (has the nb_index slot of 
+  the tp_as_number structure filled in).  
+  \versionadded{2.5}
+\end{cfuncdesc}
+
+
 \section{Sequence Protocol \label{sequence}}
 
 \begin{cfuncdesc}{int}{PySequence_Check}{PyObject *o}

Modified: stackless/trunk/Doc/api/concrete.tex
==============================================================================
--- stackless/trunk/Doc/api/concrete.tex	(original)
+++ stackless/trunk/Doc/api/concrete.tex	Mon Aug 21 11:10:05 2006
@@ -31,7 +31,7 @@
 
 \begin{cvardesc}{PyObject*}{PyType_Type}
   This is the type object for type objects; it is the same object as
-  \code{types.TypeType} in the Python layer.
+  \code{type} and \code{types.TypeType} in the Python layer.
   \withsubitem{(in module types)}{\ttindex{TypeType}}
 \end{cvardesc}
 
@@ -117,7 +117,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyInt_Type}
   This instance of \ctype{PyTypeObject} represents the Python plain
-  integer type.  This is the same object as \code{types.IntType}.
+  integer type.  This is the same object as \code{int} and
+  \code{types.IntType}.
   \withsubitem{(in modules types)}{\ttindex{IntType}}
 \end{cvardesc}
 
@@ -260,7 +261,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyLong_Type}
   This instance of \ctype{PyTypeObject} represents the Python long
-  integer type.  This is the same object as \code{types.LongType}.
+  integer type.  This is the same object as \code{long} and
+  \code{types.LongType}.
   \withsubitem{(in modules types)}{\ttindex{LongType}}
 \end{cvardesc}
 
@@ -411,7 +413,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyFloat_Type}
   This instance of \ctype{PyTypeObject} represents the Python floating
-  point type.  This is the same object as \code{types.FloatType}.
+  point type.  This is the same object as \code{float} and
+  \code{types.FloatType}.
   \withsubitem{(in modules types)}{\ttindex{FloatType}}
 \end{cvardesc}
 
@@ -520,7 +523,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyComplex_Type}
   This instance of \ctype{PyTypeObject} represents the Python complex
-  number type.
+  number type. It is the same object as \code{complex} and
+  \code{types.ComplexType}.
 \end{cvardesc}
 
 \begin{cfuncdesc}{int}{PyComplex_Check}{PyObject *p}
@@ -580,8 +584,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyString_Type}
   This instance of \ctype{PyTypeObject} represents the Python string
-  type; it is the same object as \code{types.TypeType} in the Python
-  layer.
+  type; it is the same object as \code{str} and \code{types.StringType}
+  in the Python layer.
   \withsubitem{(in module types)}{\ttindex{StringType}}.
 \end{cvardesc}
 
@@ -850,7 +854,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyUnicode_Type}
   This instance of \ctype{PyTypeObject} represents the Python Unicode
-  type.
+  type.  It is exposed to Python code as \code{unicode} and
+  \code{types.UnicodeType}.
 \end{cvardesc}
 
 The following APIs are really C macros and can be used to do fast
@@ -1555,6 +1560,26 @@
   greater than, respectively.
 \end{cfuncdesc}
 
+\begin{cfuncdesc}{int}{PyUnicode_RichCompare}{PyObject *left, 
+                                              PyObject *right, 
+                                              int op}
+
+  Rich compare two unicode strings and return one of the following:
+  \begin{itemize}
+    \item \code{NULL} in case an exception was raised
+    \item \constant{Py_True} or \constant{Py_False} for successful comparisons
+    \item \constant{Py_NotImplemented} in case the type combination is unknown
+  \end{itemize}
+
+   Note that \constant{Py_EQ} and \constant{Py_NE} comparisons can cause a
+   \exception{UnicodeWarning} in case the conversion of the arguments to
+   Unicode fails with a \exception{UnicodeDecodeError}.
+
+   Possible values for \var{op} are
+   \constant{Py_GT}, \constant{Py_GE}, \constant{Py_EQ},
+   \constant{Py_NE}, \constant{Py_LT}, and \constant{Py_LE}.
+\end{cfuncdesc}
+
 \begin{cfuncdesc}{PyObject*}{PyUnicode_Format}{PyObject *format,
                                               PyObject *args}
   Return a new string object from \var{format} and \var{args}; this
@@ -1623,8 +1648,9 @@
 
 \begin{cvardesc}{PyTypeObject}{PyBuffer_Type}
   The instance of \ctype{PyTypeObject} which represents the Python
-  buffer type; it is the same object as \code{types.BufferType} in the
-  Python layer.\withsubitem{(in module types)}{\ttindex{BufferType}}.
+  buffer type; it is the same object as \code{buffer} and 
+  \code{types.BufferType} in the Python layer.
+  \withsubitem{(in module types)}{\ttindex{BufferType}}.
 \end{cvardesc}
 
 \begin{cvardesc}{int}{Py_END_OF_BUFFER}
@@ -1698,8 +1724,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyTuple_Type}
   This instance of \ctype{PyTypeObject} represents the Python tuple
-  type; it is the same object as \code{types.TupleType} in the Python
-  layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
+  type; it is the same object as \code{tuple} and \code{types.TupleType}
+  in the Python layer.\withsubitem{(in module types)}{\ttindex{TupleType}}.
 \end{cvardesc}
 
 \begin{cfuncdesc}{int}{PyTuple_Check}{PyObject *p}
@@ -1795,8 +1821,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyList_Type}
   This instance of \ctype{PyTypeObject} represents the Python list
-  type.  This is the same object as \code{types.ListType}.
-  \withsubitem{(in module types)}{\ttindex{ListType}}
+  type.  This is the same object as \code{list} and \code{types.ListType}
+  in the Python layer.\withsubitem{(in module types)}{\ttindex{ListType}}
 \end{cvardesc}
 
 \begin{cfuncdesc}{int}{PyList_Check}{PyObject *p}
@@ -1924,7 +1950,7 @@
 \begin{cvardesc}{PyTypeObject}{PyDict_Type}
   This instance of \ctype{PyTypeObject} represents the Python
   dictionary type.  This is exposed to Python programs as
-  \code{types.DictType} and \code{types.DictionaryType}.
+  \code{dict} and \code{types.DictType}.
   \withsubitem{(in module types)}{\ttindex{DictType}\ttindex{DictionaryType}}
 \end{cvardesc}
 
@@ -2139,7 +2165,8 @@
 
 \begin{cvardesc}{PyTypeObject}{PyFile_Type}
   This instance of \ctype{PyTypeObject} represents the Python file
-  type.  This is exposed to Python programs as \code{types.FileType}.
+  type.  This is exposed to Python programs as \code{file} and
+  \code{types.FileType}.
   \withsubitem{(in module types)}{\ttindex{FileType}}
 \end{cvardesc}
 
@@ -2588,7 +2615,7 @@
 
 \begin{cvardesc}{PyTypeObject}{PySlice_Type}
   The type object for slice objects.  This is the same as
-  \code{types.SliceType}.
+  \code{slice} and \code{types.SliceType}.
   \withsubitem{(in module types)}{\ttindex{SliceType}}
 \end{cvardesc}
 

Modified: stackless/trunk/Doc/api/exceptions.tex
==============================================================================
--- stackless/trunk/Doc/api/exceptions.tex	(original)
+++ stackless/trunk/Doc/api/exceptions.tex	Mon Aug 21 11:10:05 2006
@@ -288,10 +288,11 @@
   names are \samp{PyExc_} followed by the Python exception name.
   These have the type \ctype{PyObject*}; they are all class objects.
   Their names are \cdata{PyExc_Warning}, \cdata{PyExc_UserWarning},
-  \cdata{PyExc_DeprecationWarning}, \cdata{PyExc_SyntaxWarning},
-  \cdata{PyExc_RuntimeWarning}, and \cdata{PyExc_FutureWarning}.
-  \cdata{PyExc_Warning} is a subclass of \cdata{PyExc_Exception}; the
-  other warning categories are subclasses of \cdata{PyExc_Warning}.
+  \cdata{PyExc_UnicodeWarning}, \cdata{PyExc_DeprecationWarning},
+  \cdata{PyExc_SyntaxWarning}, \cdata{PyExc_RuntimeWarning}, and
+  \cdata{PyExc_FutureWarning}.  \cdata{PyExc_Warning} is a subclass of
+  \cdata{PyExc_Exception}; the other warning categories are subclasses
+  of \cdata{PyExc_Warning}.
 
   For information about warning control, see the documentation for the
   \module{warnings} module and the \programopt{-W} option in the

Modified: stackless/trunk/Doc/api/init.tex
==============================================================================
--- stackless/trunk/Doc/api/init.tex	(original)
+++ stackless/trunk/Doc/api/init.tex	Mon Aug 21 11:10:05 2006
@@ -696,15 +696,15 @@
 \end{cfuncdesc}
 
 \begin{cfuncdesc}{int}{PyThreadState_SetAsyncExc}{long id, PyObject *exc}
-  Asynchronously raise an exception in a thread. 
+  Asynchronously raise an exception in a thread.
   The \var{id} argument is the thread id of the target thread;
   \var{exc} is the exception object to be raised.
   This function does not steal any references to \var{exc}.
-  To prevent naive misuse, you must write your own C extension 
-  to call this.  Must be called with the GIL held. 
-  Returns the number of thread states modified; if it returns a number 
-  greater than one, you're in trouble, and you should call it again 
-  with \var{exc} set to \constant{NULL} to revert the effect.
+  To prevent naive misuse, you must write your own C extension
+  to call this.  Must be called with the GIL held.
+  Returns the number of thread states modified; this is normally one, but
+  will be zero if the thread id isn't found.  If \var{exc} is
+  \constant{NULL}, the pending exception (if any) for the thread is cleared.
   This raises no exceptions.
   \versionadded{2.3}
 \end{cfuncdesc}

Modified: stackless/trunk/Doc/commontex/boilerplate.tex
==============================================================================
--- stackless/trunk/Doc/commontex/boilerplate.tex	(original)
+++ stackless/trunk/Doc/commontex/boilerplate.tex	Mon Aug 21 11:10:05 2006
@@ -5,5 +5,5 @@
 	Email: \email{docs at python.org}
 }
 
-\date{3rd August, 2006}			% XXX update before final release!
+\date{17th August, 2006}			% XXX update before final release!
 \input{patchlevel}		% include Python version information

Modified: stackless/trunk/Doc/dist/dist.tex
==============================================================================
--- stackless/trunk/Doc/dist/dist.tex	(original)
+++ stackless/trunk/Doc/dist/dist.tex	Mon Aug 21 11:10:05 2006
@@ -1992,6 +1992,7 @@
 script for this could be
 \begin{verbatim}
 from distutils.core import setup
+from distutils.extension import Extension
 setup(name='foobar',
       version='1.0',
       ext_modules=[Extension('foo', ['foo.c'])],
@@ -2006,6 +2007,7 @@
 extension:
 \begin{verbatim}
 from distutils.core import setup
+from distutils.extension import Extension
 setup(name='foobar',
       version='1.0',
       ext_modules=[Extension('foopkg.foo', ['foo.c'])],

Modified: stackless/trunk/Doc/howto/sockets.tex
==============================================================================
--- stackless/trunk/Doc/howto/sockets.tex	(original)
+++ stackless/trunk/Doc/howto/sockets.tex	Mon Aug 21 11:10:05 2006
@@ -213,34 +213,39 @@
 is a fixed length message:
 
 \begin{verbatim}
-    class mysocket:
-        '''demonstration class only 
-          - coded for clarity, not efficiency'''
-        def __init__(self, sock=None):
-            if sock is None:
-                self.sock = socket.socket(
-                    socket.AF_INET, socket.SOCK_STREAM)
-            else:
-                self.sock = sock
-        def connect(host, port):
-            self.sock.connect((host, port))
-        def mysend(msg):
-            totalsent = 0
-            while totalsent < MSGLEN:
-                sent = self.sock.send(msg[totalsent:])
-                if sent == 0:
-                    raise RuntimeError, \\
-                        "socket connection broken"
-                totalsent = totalsent + sent
-        def myreceive():
-            msg = ''
-            while len(msg) < MSGLEN:
-                chunk = self.sock.recv(MSGLEN-len(msg))
-                if chunk == '':
-                    raise RuntimeError, \\
-                        "socket connection broken"
-                msg = msg + chunk
-            return msg
+class mysocket:
+    '''demonstration class only 
+      - coded for clarity, not efficiency
+    '''
+
+    def __init__(self, sock=None):
+	if sock is None:
+	    self.sock = socket.socket(
+		socket.AF_INET, socket.SOCK_STREAM)
+	else:
+	    self.sock = sock
+
+    def connect(self, host, port):
+	self.sock.connect((host, port))
+
+    def mysend(self, msg):
+	totalsent = 0
+	while totalsent < MSGLEN:
+	    sent = self.sock.send(msg[totalsent:])
+	    if sent == 0:
+		raise RuntimeError, \\
+		    "socket connection broken"
+	    totalsent = totalsent + sent
+
+    def myreceive(self):
+	msg = ''
+	while len(msg) < MSGLEN:
+	    chunk = self.sock.recv(MSGLEN-len(msg))
+	    if chunk == '':
+		raise RuntimeError, \\
+		    "socket connection broken"
+	    msg = msg + chunk
+	return msg
 \end{verbatim}
 
 The sending code here is usable for almost any messaging scheme - in

Modified: stackless/trunk/Doc/lib/libctypes.tex
==============================================================================
--- stackless/trunk/Doc/lib/libctypes.tex	(original)
+++ stackless/trunk/Doc/lib/libctypes.tex	Mon Aug 21 11:10:05 2006
@@ -199,8 +199,13 @@
 There are, however, enough ways to crash Python with \code{ctypes}, so
 you should be careful anyway.
 
-Python integers, strings and unicode strings are the only objects that
-can directly be used as parameters in these function calls.
+\code{None}, integers, longs, byte strings and unicode strings are the
+only native Python objects that can directly be used as parameters in
+these function calls.  \code{None} is passed as a C \code{NULL} pointer,
+byte strings and unicode strings are passed as pointer to the memory
+block that contains their data (\code{char *} or \code{wchar{\_}t *}).  Python
+integers and Python longs are passed as the platforms default C
+\code{int} type, their value is masked to fit into the C type.
 
 Before we move on calling functions with other parameter types, we
 have to learn more about \code{ctypes} data types.
@@ -227,7 +232,18 @@
 \code{char}
 }
 {
-character
+1-character
+string
+}
+\lineiii{
+\class{c{\_}wchar}
+}
+{
+\code{wchar{\_}t}
+}
+{
+1-character
+unicode string
 }
 \lineiii{
 \class{c{\_}byte}
@@ -236,7 +252,7 @@
 \code{char}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}ubyte}
@@ -245,7 +261,7 @@
 \code{unsigned char}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}short}
@@ -254,7 +270,7 @@
 \code{short}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}ushort}
@@ -263,7 +279,7 @@
 \code{unsigned short}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}int}
@@ -272,7 +288,7 @@
 \code{int}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}uint}
@@ -281,7 +297,7 @@
 \code{unsigned int}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}long}
@@ -290,7 +306,7 @@
 \code{long}
 }
 {
-integer
+int/long
 }
 \lineiii{
 \class{c{\_}ulong}
@@ -299,7 +315,7 @@
 \code{unsigned long}
 }
 {
-long
+int/long
 }
 \lineiii{
 \class{c{\_}longlong}
@@ -309,7 +325,7 @@
 \code{long long}
 }
 {
-long
+int/long
 }
 \lineiii{
 \class{c{\_}ulonglong}
@@ -319,7 +335,7 @@
 \code{unsigned long long}
 }
 {
-long
+int/long
 }
 \lineiii{
 \class{c{\_}float}
@@ -368,8 +384,8 @@
 \code{void *}
 }
 {
-integer or
-\code{None}
+int/long
+or \code{None}
 }
 \end{tableiii}
 \end{quote}
@@ -554,11 +570,11 @@
 
 \subsubsection{Return types\label{ctypes-return-types}}
 
-By default functions are assumed to return integers.  Other return
-types can be specified by setting the \member{restype} attribute of the
-function object.
+By default functions are assumed to return the C \code{int} type.  Other
+return types can be specified by setting the \member{restype} attribute of
+the function object.
 
-Here is a more advanced example, it uses the strchr function, which
+Here is a more advanced example, it uses the \code{strchr} function, which
 expects a string pointer and a char, and returns a pointer to a
 string:
 \begin{verbatim}
@@ -1611,8 +1627,8 @@
 
 \begin{datadescni}{pythonapi}
 An instance of \class{PyDLL} that exposes Python C api functions as
-attributes.  Note that all these functions are assumed to return
-integers, which is of course not always the truth, so you have to
+attributes.  Note that all these functions are assumed to return C
+\code{int}, which is of course not always the truth, so you have to
 assign the correct \member{restype} attribute to use these functions.
 \end{datadescni}
 
@@ -1642,8 +1658,8 @@
 anything.
 
 It is possible to assign a callable Python object that is not a
-ctypes type, in this case the function is assumed to return an
-integer, and the callable will be called with this integer,
+ctypes type, in this case the function is assumed to return a
+C \code{int}, and the callable will be called with this integer,
 allowing to do further processing or error checking.  Using this
 is deprecated, for more flexible postprocessing or error checking
 use a ctypes data type as \member{restype} and assign a callable to the
@@ -2283,9 +2299,12 @@
 or error information for a function or method call.
 \end{classdesc*}
 
-\begin{classdesc*}{py_object}
-Represents the C \code{PyObject *} datatype.
-\end{classdesc*}
+\code{py{\_}object} : classdesc*
+\begin{quote}
+
+Represents the C \code{PyObject *} datatype.  Calling this with an
+without an argument creates a \code{NULL} \code{PyObject *} pointer.
+\end{quote}
 
 The \code{ctypes.wintypes} module provides quite some other Windows
 specific data types, for example \code{HWND}, \code{WPARAM}, or \code{DWORD}.
@@ -2324,9 +2343,9 @@
 the second item specifies the type of the field; it can be any
 ctypes data type.
 
-For integer type fields, a third optional item can be given.  It
-must be a small positive integer defining the bit width of the
-field.
+For integer type fields like \class{c{\_}int}, a third optional item can
+be given.  It must be a small positive integer defining the bit
+width of the field.
 
 Field names must be unique within one structure or union.  This is
 not checked, only one field can be accessed when names are

Modified: stackless/trunk/Doc/lib/libexcs.tex
==============================================================================
--- stackless/trunk/Doc/lib/libexcs.tex	(original)
+++ stackless/trunk/Doc/lib/libexcs.tex	Mon Aug 21 11:10:05 2006
@@ -456,6 +456,11 @@
 \versionadded{2.5}
 \end{excdesc}
 
+\begin{excdesc}{UnicodeWarning}
+Base class for warnings related to Unicode.
+\versionadded{2.5}
+\end{excdesc}
+
 The class hierarchy for built-in exceptions is:
 
 \verbatiminput{../../Lib/test/exception_hierarchy.txt}

Modified: stackless/trunk/Doc/lib/libinspect.tex
==============================================================================
--- stackless/trunk/Doc/lib/libinspect.tex	(original)
+++ stackless/trunk/Doc/lib/libinspect.tex	Mon Aug 21 11:10:05 2006
@@ -291,18 +291,18 @@
 \end{funcdesc}
 
 \begin{funcdesc}{formatargspec}{args\optional{, varargs, varkw, defaults,
-      argformat, varargsformat, varkwformat, defaultformat}}
+      formatarg, formatvarargs, formatvarkw, formatvalue, join}}
 
   Format a pretty argument spec from the four values returned by
-  \function{getargspec()}.  The other four arguments are the
+  \function{getargspec()}.  The format* arguments are the
   corresponding optional formatting functions that are called to turn
   names and values into strings.
 \end{funcdesc}
 
 \begin{funcdesc}{formatargvalues}{args\optional{, varargs, varkw, locals,
-      argformat, varargsformat, varkwformat, valueformat}}
+      formatarg, formatvarargs, formatvarkw, formatvalue, join}}
   Format a pretty argument spec from the four values returned by
-  \function{getargvalues()}.  The other four arguments are the
+  \function{getargvalues()}.  The format* arguments are the
   corresponding optional formatting functions that are called to turn
   names and values into strings.
 \end{funcdesc}

Modified: stackless/trunk/Doc/lib/liblinecache.tex
==============================================================================
--- stackless/trunk/Doc/lib/liblinecache.tex	(original)
+++ stackless/trunk/Doc/lib/liblinecache.tex	Mon Aug 21 11:10:05 2006
@@ -38,7 +38,7 @@
 \begin{funcdesc}{checkcache}{\optional{filename}}
 Check the cache for validity.  Use this function if files in the cache 
 may have changed on disk, and you require the updated version.  If
-\var{filename} is omitted, it will check the whole cache entries.
+\var{filename} is omitted, it will check all the entries in the cache.
 \end{funcdesc}
 
 Example:

Modified: stackless/trunk/Doc/lib/libturtle.tex
==============================================================================
--- stackless/trunk/Doc/lib/libturtle.tex	(original)
+++ stackless/trunk/Doc/lib/libturtle.tex	Mon Aug 21 11:10:05 2006
@@ -253,12 +253,13 @@
 
 \subsection{Turtle, Pen and RawPen Objects \label{pen-rawpen-objects}}
 
-\class{Turtle}, \class{Pen} and \class{RawPen} objects have all the
-global functions described above, except for \function{demo()} as
-methods, which manipulate the given pen.
+Most of the global functions available in the module are also
+available as methods of the \class{Turtle}, \class{Pen} and
+\class{RawPen} classes, affecting only the state of the given pen.
 
 The only method which is more powerful as a method is
-\function{degrees()}.
+\function{degrees()}, which takes an optional argument letting 
+you specify the number of units corresponding to a full circle:
 
 \begin{methoddesc}{degrees}{\optional{fullcircle}}
 \var{fullcircle} is by default 360. This can cause the pen to have any

Modified: stackless/trunk/Doc/lib/libunittest.tex
==============================================================================
--- stackless/trunk/Doc/lib/libunittest.tex	(original)
+++ stackless/trunk/Doc/lib/libunittest.tex	Mon Aug 21 11:10:05 2006
@@ -10,19 +10,19 @@
 
 \versionadded{2.1}
 
-The Python unit testing framework, often referred to as ``PyUnit,'' is
+The Python unit testing framework, sometimes referred to as ``PyUnit,'' is
 a Python language version of JUnit, by Kent Beck and Erich Gamma.
 JUnit is, in turn, a Java version of Kent's Smalltalk testing
 framework.  Each is the de facto standard unit testing framework for
 its respective language.
 
-PyUnit supports test automation, sharing of setup and shutdown code
-for tests, aggregation of tests into collections, and independence of
+\module{unittest} supports test automation, sharing of setup and shutdown
+code for tests, aggregation of tests into collections, and independence of
 the tests from the reporting framework.  The \module{unittest} module
 provides classes that make it easy to support these qualities for a
 set of tests.
 
-To achieve this, PyUnit supports some important concepts:
+To achieve this, \module{unittest} supports some important concepts:
 
 \begin{definitions}
 \term{test fixture}
@@ -33,10 +33,9 @@
 
 \term{test case}
 A \dfn{test case} is the smallest unit of testing.  It checks for a
-specific response to a particular set of inputs.  PyUnit provides a
-base class, \class{TestCase}, which may be used to create new test
-cases. You may provide your own implementation that does not subclass
-from \class{TestCase}, of course.
+specific response to a particular set of inputs.  \module{unittest}
+provides a base class, \class{TestCase}, which may be used to create
+new test cases.
 
 \term{test suite}
 A \dfn{test suite} is a collection of test cases, test suites, or
@@ -54,8 +53,8 @@
 The test case and test fixture concepts are supported through the
 \class{TestCase} and \class{FunctionTestCase} classes; the former
 should be used when creating new tests, and the latter can be used when
-integrating existing test code with a PyUnit-driven framework.  When
-building test fixtures using \class{TestCase}, the \method{setUp()}
+integrating existing test code with a \module{unittest}-driven framework.
+When building test fixtures using \class{TestCase}, the \method{setUp()}
 and \method{tearDown()} methods can be overridden to provide
 initialization and cleanup for the fixture.  With
 \class{FunctionTestCase}, existing functions can be passed to the
@@ -74,19 +73,17 @@
 A test runner is an object that provides a single method,
 \method{run()}, which accepts a \class{TestCase} or \class{TestSuite}
 object as a parameter, and returns a result object.  The class
-\class{TestResult} is provided for use as the result object.  PyUnit
-provide the \class{TextTestRunner} as an example test runner which
-reports test results on the standard error stream by default.
-Alternate runners can be implemented for other environments (such as
-graphical environments) without any need to derive from a specific
-class.
+\class{TestResult} is provided for use as the result object.
+\module{unittest} provides the \class{TextTestRunner} as an example
+test runner which reports test results on the standard error stream by
+default.  Alternate runners can be implemented for other environments
+(such as graphical environments) without any need to derive from a
+specific class.
 
 
 \begin{seealso}
   \seemodule{doctest}{Another test-support module with a very
                       different flavor.}
-  \seetitle[http://pyunit.sourceforge.net/]{PyUnit Web Site}{The
-            source for further information on PyUnit.}
   \seetitle[http://www.XProgramming.com/testfram.htm]{Simple Smalltalk
             Testing: With Patterns}{Kent Beck's original paper on
             testing frameworks using the pattern shared by
@@ -166,7 +163,7 @@
 with:
 
 \begin{verbatim}
-suite = unittest.makeSuite(TestSequenceFunctions)
+suite = unittest.TestLoader().loadTestsFromTestCase(TestSequenceFunctions)
 unittest.TextTestRunner(verbosity=2).run(suite)
 \end{verbatim}
 
@@ -194,8 +191,8 @@
 
 The basic building blocks of unit testing are \dfn{test cases} ---
 single scenarios that must be set up and checked for correctness.  In
-PyUnit, test cases are represented by instances of the
-\class{TestCase} class in the \refmodule{unittest} module. To make
+\module{unittest}, test cases are represented by instances of
+\module{unittest}'s \class{TestCase} class. To make
 your own test cases you must write subclasses of \class{TestCase}, or
 use \class{FunctionTestCase}.
 
@@ -207,7 +204,7 @@
 self contained, such that it can be run either in isolation or in
 arbitrary combination with any number of other test cases.
 
-The simplest test case subclass will simply override the
+The simplest \class{TestCase} subclass will simply override the
 \method{runTest()} method in order to perform specific testing code:
 
 \begin{verbatim}
@@ -221,12 +218,13 @@
 
 Note that in order to test something, we use the one of the
 \method{assert*()} or \method{fail*()} methods provided by the
-\class{TestCase} base class.  If the test fails when the test case
-runs, an exception will be raised, and the testing framework will
-identify the test case as a \dfn{failure}.  Other exceptions that do
-not arise from checks made through the \method{assert*()} and
-\method{fail*()} methods are identified by the testing framework as
-\dfn{errors}.
+\class{TestCase} base class.  If the test fails, an exception will be
+raised, and \module{unittest} will identify the test case as a
+\dfn{failure}.  Any other exceptions will be treated as \dfn{errors}.
+This helps you identify where the problem is: \dfn{failures} are caused by
+incorrect results - a 5 where you expected a 6. \dfn{Errors} are caused by
+incorrect code - e.g., a \exception{TypeError} caused by an incorrect
+function call.
 
 The way to run a test case will be described later.  For now, note
 that to construct an instance of such a test case, we call its
@@ -237,7 +235,7 @@
 \end{verbatim}
 
 Now, such test cases can be numerous, and their set-up can be
-repetitive.  In the above case, constructing a ``Widget'' in each of
+repetitive.  In the above case, constructing a \class{Widget} in each of
 100 Widget test case subclasses would mean unsightly duplication.
 
 Luckily, we can factor out such set-up code by implementing a method
@@ -283,7 +281,7 @@
 \end{verbatim}
 
 If \method{setUp()} succeeded, the \method{tearDown()} method will be
-run regardless of whether or not \method{runTest()} succeeded.
+run whether \method{runTest()} succeeded or not.
 
 Such a working environment for the testing code is called a
 \dfn{fixture}.
@@ -292,8 +290,8 @@
 we would end up subclassing \class{SimpleWidgetTestCase} into many
 small one-method classes such as
 \class{DefaultWidgetSizeTestCase}.  This is time-consuming and
-discouraging, so in the same vein as JUnit, PyUnit provides a simpler
-mechanism:
+discouraging, so in the same vein as JUnit, \module{unittest} provides
+a simpler mechanism:
 
 \begin{verbatim}
 import unittest
@@ -329,9 +327,9 @@
 \end{verbatim}
 
 Test case instances are grouped together according to the features
-they test.  PyUnit provides a mechanism for this: the \class{test
-suite}, represented by the class \class{TestSuite} in the
-\refmodule{unittest} module:
+they test.  \module{unittest} provides a mechanism for this: the
+\dfn{test suite}, represented by \module{unittest}'s \class{TestSuite}
+class:
 
 \begin{verbatim}
 widgetTestSuite = unittest.TestSuite()
@@ -354,28 +352,30 @@
 or even:
 
 \begin{verbatim}
-class WidgetTestSuite(unittest.TestSuite):
-    def __init__(self):
-        unittest.TestSuite.__init__(self,map(WidgetTestCase,
-                                              ("testDefaultSize",
-                                               "testResize")))
-\end{verbatim}
+def suite():
+    tests = ["testDefaultSize", "testResize"]
 
-(The latter is admittedly not for the faint-hearted!)
+    return unittest.TestSuite(map(WidgetTestCase, tests))
+\end{verbatim}
 
 Since it is a common pattern to create a \class{TestCase} subclass
-with many similarly named test functions, there is a convenience
-function called \function{makeSuite()} that constructs a test suite
-that comprises all of the test cases in a test case class:
+with many similarly named test functions, \module{unittest} provides a
+\class{TestLoader} class that can be used to automate the process of
+creating a test suite and populating it with individual tests.
+For example,
 
 \begin{verbatim}
-suite = unittest.makeSuite(WidgetTestCase)
+suite = unittest.TestLoader().loadTestsFromTestCase(WidgetTestCase)
 \end{verbatim}
 
-Note that when using the \function{makeSuite()} function, the order in
-which the various test cases will be run by the test suite is the
-order determined by sorting the test function names using the
-\function{cmp()} built-in function.
+will create a test suite that will run
+\code{WidgetTestCase.testDefaultSize()} and \code{WidgetTestCase.testResize}.
+\class{TestLoader} uses the \code{'test'} method name prefix to identify
+test methods automatically.
+
+Note that the order in which the various test cases will be run is
+determined by sorting the test function names with the built-in
+\function{cmp()} function.
 
 Often it is desirable to group suites of test cases together, so as to
 run tests for the whole system at once.  This is easy, since
@@ -385,13 +385,13 @@
 \begin{verbatim}
 suite1 = module1.TheTestSuite()
 suite2 = module2.TheTestSuite()
-alltests = unittest.TestSuite((suite1, suite2))
+alltests = unittest.TestSuite([suite1, suite2])
 \end{verbatim}
 
 You can place the definitions of test cases and test suites in the
 same modules as the code they are to test (such as \file{widget.py}),
 but there are several advantages to placing the test code in a
-separate module, such as \file{widgettests.py}:
+separate module, such as \file{test_widget.py}:
 
 \begin{itemize}
   \item The test module can be run standalone from the command line.
@@ -412,13 +412,12 @@
             \label{legacy-unit-tests}}
 
 Some users will find that they have existing test code that they would
-like to run from PyUnit, without converting every old test function to
-a \class{TestCase} subclass.
+like to run from \module{unittest}, without converting every old test
+function to a \class{TestCase} subclass.
 
-For this reason, PyUnit provides a \class{FunctionTestCase} class.
-This subclass of \class{TestCase} can be used to wrap an existing test
-function.  Set-up and tear-down functions can also optionally be
-wrapped.
+For this reason, \module{unittest} provides a \class{FunctionTestCase}
+class.  This subclass of \class{TestCase} can be used to wrap an existing
+test function.  Set-up and tear-down functions can also be provided.
 
 Given the following test function:
 
@@ -436,7 +435,8 @@
 \end{verbatim}
 
 If there are additional set-up and tear-down methods that should be
-called as part of the test case's operation, they can also be provided:
+called as part of the test case's operation, they can also be provided
+like so:
 
 \begin{verbatim}
 testcase = unittest.FunctionTestCase(testSomething,
@@ -444,9 +444,19 @@
                                      tearDown=deleteSomethingDB)
 \end{verbatim}
 
-\note{PyUnit supports the use of \exception{AssertionError}
-as an indicator of test failure, but does not recommend it.  Future
-versions may treat \exception{AssertionError} differently.}
+To make migrating existing test suites easier, \module{unittest}
+supports tests raising \exception{AssertionError} to indicate test failure.
+However, it is recommended that you use the explicit
+\method{TestCase.fail*()} and \method{TestCase.assert*()} methods instead,
+as future versions of \module{unittest} may treat \exception{AssertionError}
+differently.
+
+\note{Even though \class{FunctionTestCase} can be used to quickly convert
+an existing test base over to a \module{unittest}-based system, this
+approach is not recommended.  Taking the time to set up proper
+\class{TestCase} subclasses will make future test refactorings infinitely
+easier.}
+
 
 
 \subsection{Classes and functions
@@ -454,11 +464,12 @@
 
 \begin{classdesc}{TestCase}{}
   Instances of the \class{TestCase} class represent the smallest
-  testable units in a set of tests.  This class is intended to be used
-  as a base class, with specific tests being implemented by concrete
-  subclasses.  This class implements the interface needed by the test
-  runner to allow it to drive the test, and methods that the test code
-  can use to check for and report various kinds of failures.
+  testable units in the \module{unittest} universe.  This class is
+  intended to be used as a base class, with specific tests being
+  implemented by concrete subclasses.  This class implements the
+  interface needed by the test runner to allow it to drive the
+  test, and methods that the test code can use to check for and
+  report various kinds of failure.
 \end{classdesc}
 
 \begin{classdesc}{FunctionTestCase}{testFunc\optional{,
@@ -474,33 +485,33 @@
 \begin{classdesc}{TestSuite}{\optional{tests}}
   This class represents an aggregation of individual tests cases and
   test suites.  The class presents the interface needed by the test
-  runner to allow it to be run as any other test case, but all the
-  contained tests and test suites are executed.  Additional methods
-  are provided to add test cases and suites to the aggregation.  If
-  \var{tests} is given, it must be a sequence of individual tests that
-  will be added to the suite.
+  runner to allow it to be run as any other test case.  Running a
+  \class{TestSuite} instance is the same as iterating over the suite,
+  running each test individually.
+  
+  If \var{tests} is given, it must be an iterable of individual test cases or
+  other test suites that will be used to build the suite initially.
+  Additional methods are provided to add test cases and suites to the
+  collection later on.
 \end{classdesc}
 
 \begin{classdesc}{TestLoader}{}
   This class is responsible for loading tests according to various
   criteria and returning them wrapped in a \class{TestSuite}.
   It can load all tests within a given module or \class{TestCase}
-  class.  When loading from a module, it considers all
-  \class{TestCase}-derived classes.  For each such class, it creates
-  an instance for each method with a name beginning with the string
-  \samp{test}.
+  subclass.
 \end{classdesc}
 
 \begin{datadesc}{defaultTestLoader}
-  Instance of the \class{TestLoader} class which can be shared.  If no
+  Instance of the \class{TestLoader} class intended to be shared.  If no
   customization of the \class{TestLoader} is needed, this instance can
-  always be used instead of creating new instances.
+  be used instead of repeatedly creating new instances.
 \end{datadesc}
 
 \begin{classdesc}{TextTestRunner}{\optional{stream\optional{,
                   descriptions\optional{, verbosity}}}}
   A basic test runner implementation which prints results on standard
-  output.  It has a few configurable parameters, but is essentially
+  error.  It has a few configurable parameters, but is essentially
   very simple.  Graphical applications which run test suites should
   provide alternate implementations.
 \end{classdesc}
@@ -510,7 +521,8 @@
                  testRunner\optional{, testRunner}}}}}}
   A command-line program that runs a set of tests; this is primarily
   for making test modules conveniently executable.  The simplest use
-  for this function is:
+  for this function is to include the following line at the end of a
+  test script:
 
 \begin{verbatim}
 if __name__ == '__main__':
@@ -518,10 +530,11 @@
 \end{verbatim}
 \end{funcdesc}
 
-In some cases, the existing tests may have be written using the
+In some cases, the existing tests may have been written using the
 \refmodule{doctest} module.  If so, that module provides a 
 \class{DocTestSuite} class that can automatically build
-\class{unittest.TestSuite} instances from the existing test code.
+\class{unittest.TestSuite} instances from the existing
+\module{doctest}-based tests.
 \versionadded{2.3}
 
 
@@ -538,7 +551,7 @@
 check conditions and report failures, and some inquiry methods
 allowing information about the test itself to be gathered.
 
-Methods in the first group are:
+Methods in the first group (running the test) are:
 
 \begin{methoddesc}[TestCase]{setUp}{}
   Method called to prepare the test fixture.  This is called
@@ -562,8 +575,10 @@
   Run the test, collecting the result into the test result object
   passed as \var{result}.  If \var{result} is omitted or \constant{None},
   a temporary result object is created and used, but is not made
-  available to the caller.  This is equivalent to simply calling the
-  \class{TestCase} instance.
+  available to the caller.
+  
+  The same effect may be had by simply calling the \class{TestCase}
+  instance.
 \end{methoddesc}
 
 \begin{methoddesc}[TestCase]{debug}{}
@@ -664,10 +679,8 @@
 information on the test:
 
 \begin{methoddesc}[TestCase]{countTestCases}{}
-  Return the number of tests represented by the this test object.  For
-  \class{TestCase} instances, this will always be \code{1}, but this
-  method is also implemented by the \class{TestSuite} class, which can
-  return larger values.
+  Return the number of tests represented by this test object.  For
+  \class{TestCase} instances, this will always be \code{1}.
 \end{methoddesc}
 
 \begin{methoddesc}[TestCase]{defaultTestResult}{}
@@ -678,7 +691,7 @@
 \begin{methoddesc}[TestCase]{id}{}
   Return a string identifying the specific test case.  This is usually
   the full name of the test method, including the module and class
-  names.
+  name.
 \end{methoddesc}
 
 \begin{methoddesc}[TestCase]{shortDescription}{}
@@ -694,21 +707,23 @@
 
 \class{TestSuite} objects behave much like \class{TestCase} objects,
 except they do not actually implement a test.  Instead, they are used
-to aggregate tests into groups that should be run together.  Some
-additional methods are available to add tests to \class{TestSuite}
+to aggregate tests into groups of tests that should be run together.
+Some additional methods are available to add tests to \class{TestSuite}
 instances:
 
 \begin{methoddesc}[TestSuite]{addTest}{test}
-  Add a \class{TestCase} or \class{TestSuite} to the set of tests that
-  make up the suite.
+  Add a \class{TestCase} or \class{TestSuite} to the suite.
 \end{methoddesc}
 
 \begin{methoddesc}[TestSuite]{addTests}{tests}
-  Add all the tests from a sequence of \class{TestCase} and
+  Add all the tests from an iterable of \class{TestCase} and
   \class{TestSuite} instances to this test suite.
+  
+  This is equivalent to iterating over \var{tests}, calling
+  \method{addTest()} for each element.
 \end{methoddesc}
 
-The \method{run()} method is also slightly different:
+\class{TestSuite} shares the following methods with \class{TestCase}:
 
 \begin{methoddesc}[TestSuite]{run}{result}
   Run the tests associated with this suite, collecting the result into
@@ -717,6 +732,17 @@
   result object to be passed in.
 \end{methoddesc}
 
+\begin{methoddesc}[TestSuite]{debug}{}
+  Run the tests associated with this suite without collecting the result.
+  This allows exceptions raised by the test to be propagated to the caller
+  and can be used to support running tests under a debugger.
+\end{methoddesc}
+
+\begin{methoddesc}[TestSuite]{countTestCases}{}
+  Return the number of tests represented by this test object, including
+  all individual tests and sub-suites.
+\end{methoddesc}
+
 In the typical usage of a \class{TestSuite} object, the \method{run()}
 method is invoked by a \class{TestRunner} rather than by the end-user
 test harness.
@@ -727,7 +753,7 @@
 
 A \class{TestResult} object stores the results of a set of tests.  The
 \class{TestCase} and \class{TestSuite} classes ensure that results are
-properly stored; test authors do not need to worry about recording the
+properly recorded; test authors do not need to worry about recording the
 outcome of tests.
 
 Testing frameworks built on top of \refmodule{unittest} may want
@@ -745,28 +771,41 @@
 be of interest when inspecting the results of running a set of tests:
 
 \begin{memberdesc}[TestResult]{errors}
-  A list containing pairs of \class{TestCase} instances and the
-  formatted tracebacks for tests which raised an exception but did not
-  signal a test failure.
+  A list containing 2-tuples of \class{TestCase} instances and
+  formatted tracebacks. Each tuple represents a test which raised an
+  unexpected exception.
   \versionchanged[Contains formatted tracebacks instead of
                   \function{sys.exc_info()} results]{2.2}
 \end{memberdesc}
 
 \begin{memberdesc}[TestResult]{failures}
-  A list containing pairs of \class{TestCase} instances and the
-  formatted tracebacks for tests which signalled a failure in the code
-  under test.
+  A list containing 2-tuples of \class{TestCase} instances and
+  formatted tracebacks. Each tuple represents a test where a failure
+  was explicitly signalled using the \method{TestCase.fail*()} or
+  \method{TestCase.assert*()} methods.
   \versionchanged[Contains formatted tracebacks instead of
                   \function{sys.exc_info()} results]{2.2}
 \end{memberdesc}
 
 \begin{memberdesc}[TestResult]{testsRun}
-  The number of tests which have been started.
+  The total number of tests run so far.
 \end{memberdesc}
 
 \begin{methoddesc}[TestResult]{wasSuccessful}{}
-  Returns true if all tests run so far have passed, otherwise returns
-  false.
+  Returns \constant{True} if all tests run so far have passed,
+  otherwise returns \constant{False}.
+\end{methoddesc}
+
+\begin{methoddesc}[TestResult]{stop}{}
+  This method can be called to signal that the set of tests being run
+  should be aborted by setting the \class{TestResult}'s \code{shouldStop}
+  attribute to \constant{True}.  \class{TestRunner} objects should respect
+  this flag and return without running any additional tests.
+  
+  For example, this feature is used by the \class{TextTestRunner} class
+  to stop the test framework when the user signals an interrupt from
+  the keyboard.  Interactive tools which provide \class{TestRunner}
+  implementations can use this in a similar manner.
 \end{methoddesc}
 
 
@@ -786,10 +825,9 @@
 \end{methoddesc}
 
 \begin{methoddesc}[TestResult]{addError}{test, err}
-  Called when the test case \var{test} raises an exception without
-  signalling a test failure.  \var{err} is a tuple of the form
-  returned by \function{sys.exc_info()}:  \code{(\var{type},
-  \var{value}, \var{traceback})}.
+  Called when the test case \var{test} raises an unexpected exception
+  \var{err} is a tuple of the form returned by \function{sys.exc_info()}:
+  \code{(\var{type}, \var{value}, \var{traceback})}.
 \end{methoddesc}
 
 \begin{methoddesc}[TestResult]{addFailure}{test, err}
@@ -800,23 +838,10 @@
 \end{methoddesc}
 
 \begin{methoddesc}[TestResult]{addSuccess}{test}
-  This method is called for a test that does not fail; \var{test} is
-  the test case object.
+  Called when the test case \var{test} succeeds.
 \end{methoddesc}
 
 
-One additional method is available for \class{TestResult} objects:
-
-\begin{methoddesc}[TestResult]{stop}{}
-  This method can be called to signal that the set of tests being run
-  should be aborted.  Once this has been called, the
-  \class{TestRunner} object return to its caller without running any
-  additional tests.  This is used by the \class{TextTestRunner} class
-  to stop the test framework when the user signals an interrupt from
-  the keyboard.  Interactive tools which provide runners can use this
-  in a similar manner.
-\end{methoddesc}
-
 
 \subsection{TestLoader Objects
             \label{testloader-objects}}
@@ -824,15 +849,15 @@
 The \class{TestLoader} class is used to create test suites from
 classes and modules.  Normally, there is no need to create an instance
 of this class; the \refmodule{unittest} module provides an instance
-that can be shared as the \code{defaultTestLoader} module attribute.
-Using a subclass or instance would allow customization of some
+that can be shared as \code{unittest.defaultTestLoader}.
+Using a subclass or instance, however, allows customization of some
 configurable properties.
 
 \class{TestLoader} objects have the following methods:
 
 \begin{methoddesc}[TestLoader]{loadTestsFromTestCase}{testCaseClass}
   Return a suite of all tests cases contained in the
-  \class{TestCase}-derived class \class{testCaseClass}.
+  \class{TestCase}-derived \class{testCaseClass}.
 \end{methoddesc}
 
 \begin{methoddesc}[TestLoader]{loadTestsFromModule}{module}
@@ -842,7 +867,7 @@
   method defined for the class.
 
   \warning{While using a hierarchy of
-  \class{Testcase}-derived classes can be convenient in sharing
+  \class{TestCase}-derived classes can be convenient in sharing
   fixtures and helper functions, defining test methods on base classes
   that are not intended to be instantiated directly does not play well
   with this method.  Doing so, however, can be useful when the
@@ -853,21 +878,23 @@
   Return a suite of all tests cases given a string specifier.
 
   The specifier \var{name} is a ``dotted name'' that may resolve
-  either to a module, a test case class, a test method within a test
-  case class, or a callable object which returns a \class{TestCase} or
-  \class{TestSuite} instance.  For example, if you have a module
-  \module{SampleTests} containing a \class{TestCase}-derived class
-  \class{SampleTestCase} with three test methods (\method{test_one()},
-  \method{test_two()}, and \method{test_three()}), the specifier
-  \code{'SampleTests.SampleTestCase'} would cause this method to
-  return a suite which will run all three test methods.  Using the
-  specifier \code{'SampleTests.SampleTestCase.test_two'} would cause
-  it to return a test suite which will run only the
+  either to a module, a test case class, a \class{TestSuite} instance,
+  a test method within a test case class, or a callable object which
+  returns a \class{TestCase} or \class{TestSuite} instance.
+
+  For example, if you have a module \module{SampleTests} containing a
+  \class{TestCase}-derived class \class{SampleTestCase} with three test
+  methods (\method{test_one()}, \method{test_two()}, and
+  \method{test_three()}), the specifier \code{'SampleTests.SampleTestCase'}
+  would cause this method to return a suite which will run all three test
+  methods.  Using the specifier \code{'SampleTests.SampleTestCase.test_two'}
+  would cause it to return a test suite which will run only the
   \method{test_two()} test method.  The specifier can refer to modules
   and packages which have not been imported; they will be imported as
   a side-effect.
 
-  The method optionally resolves \var{name} relative to a given module.
+  The method optionally resolves \var{name} relative to the given
+  \var{module}.
 \end{methoddesc}
 
 \begin{methoddesc}[TestLoader]{loadTestsFromNames}{names\optional{, module}}
@@ -888,17 +915,22 @@
 \begin{memberdesc}[TestLoader]{testMethodPrefix}
   String giving the prefix of method names which will be interpreted
   as test methods.  The default value is \code{'test'}.
+  
+  This affects \method{getTestCaseNames()} and all the
+  \method{loadTestsFrom*()} methods.
 \end{memberdesc}
 
 \begin{memberdesc}[TestLoader]{sortTestMethodsUsing}
   Function to be used to compare method names when sorting them in
-  \method{getTestCaseNames()}.  The default value is the built-in
-  \function{cmp()} function; it can be set to \constant{None} to disable
-  the sort.
+  \method{getTestCaseNames()} and all the \method{loadTestsFrom*()} methods.
+  The default value is the built-in \function{cmp()} function; the attribute
+  can also be set to \constant{None} to disable the sort.
 \end{memberdesc}
 
 \begin{memberdesc}[TestLoader]{suiteClass}
   Callable object that constructs a test suite from a list of tests.
   No methods on the resulting object are needed.  The default value is
   the \class{TestSuite} class.
+  
+  This affects all the \method{loadTestsFrom*()} methods.
 \end{memberdesc}

Modified: stackless/trunk/Doc/lib/libwarnings.tex
==============================================================================
--- stackless/trunk/Doc/lib/libwarnings.tex	(original)
+++ stackless/trunk/Doc/lib/libwarnings.tex	Mon Aug 21 11:10:05 2006
@@ -76,6 +76,9 @@
 
 \lineii{ImportWarning}{Base category for warnings triggered during the
 process of importing a module (ignored by default).}
+
+\lineii{UnicodeWarning}{Base category for warnings related to Unicode.}
+
 \end{tableii}
 
 While these are technically built-in exceptions, they are documented

Modified: stackless/trunk/Doc/ref/ref2.tex
==============================================================================
--- stackless/trunk/Doc/ref/ref2.tex	(original)
+++ stackless/trunk/Doc/ref/ref2.tex	Mon Aug 21 11:10:05 2006
@@ -56,7 +56,7 @@
 
 A physical line is a sequence of characters terminated by an end-of-line
 sequence.  In source files, any of the standard platform line
-termination sequences can be used - the \UNIX form using \ASCII{} LF
+termination sequences can be used - the \UNIX{} form using \ASCII{} LF
 (linefeed), the Windows form using the \ASCII{} sequence CR LF (return
 followed by linefeed), or the Macintosh form using the \ASCII{} CR
 (return) character.  All of these forms can be used equally, regardless

Modified: stackless/trunk/Doc/ref/ref3.tex
==============================================================================
--- stackless/trunk/Doc/ref/ref3.tex	(original)
+++ stackless/trunk/Doc/ref/ref3.tex	Mon Aug 21 11:10:05 2006
@@ -1307,6 +1307,11 @@
 since the dictionary implementation requires that a key's hash value
 is immutable (if the object's hash value changes, it will be in the
 wrong hash bucket).
+
+\versionchanged[\method{__hash__()} may now also return a long
+integer object; the 32-bit integer is then derived from the hash
+of that object]{2.5}
+
 \withsubitem{(object method)}{\ttindex{__cmp__()}}
 \end{methoddesc}
 

Modified: stackless/trunk/Doc/whatsnew/whatsnew25.tex
==============================================================================
--- stackless/trunk/Doc/whatsnew/whatsnew25.tex	(original)
+++ stackless/trunk/Doc/whatsnew/whatsnew25.tex	Mon Aug 21 11:10:05 2006
@@ -3,10 +3,9 @@
 % $Id$
 
 % Fix XXX comments
-% Count up the patches and bugs
 
 \title{What's New in Python 2.5}
-\release{0.4}
+\release{1.0}
 \author{A.M. Kuchling}
 \authoraddress{\email{amk at amk.ca}}
 
@@ -39,11 +38,16 @@
 language feature or another; none of them are broad modifications to
 Python's semantics.
 
+As well as the language and library additions, other improvements and
+bugfixes were made throughout the source tree.  A search through the
+SVN change logs finds there were 353 patches applied and 458 bugs
+fixed between Python 2.4 and 2.5.  (Both figures are likely to be
+underestimates.)  
+
 This article doesn't try to be a complete specification of the new
 features; instead changes are briefly introduced using helpful
 examples.  For full details, you should always refer to the
-documentation for Python 2.5.
-% XXX add hyperlink when the documentation becomes available online.
+documentation for Python 2.5 at \url{http://docs.python.org}.
 If you want to understand the complete implementation and design
 rationale, refer to the PEP for a particular new feature.
 
@@ -746,7 +750,6 @@
 database, or rolled back, meaning that the changes are all discarded
 and the database is unchanged.  See any database textbook for more
 information.)
-% XXX find a shorter reference?
 
 Let's assume there's an object representing a database connection.
 Our goal will be to let the user write code like this:
@@ -1094,10 +1097,10 @@
 
 \item Both 8-bit and Unicode strings have new \method{partition(sep)} 
 and \method{rpartition(sep)} methods that simplify a common use case.
+
 The \method{find(S)} method is often used to get an index which is
 then used to slice the string and obtain the pieces that are before
 and after the separator.  
-
 \method{partition(sep)} condenses this
 pattern into a single method call that returns a 3-tuple containing
 the substring before the separator, the separator itself, and the
@@ -1159,6 +1162,15 @@
 all of the values returned by the iterator evaluate as true.
 (Suggested by Guido van~Rossum, and implemented by Raymond Hettinger.)
 
+\item The result of a class's \method{__hash__()} method can now 
+be either a long integer or a regular integer.  If a long integer is
+returned, the hash of that value is taken.  In earlier versions the
+hash value was required to be a regular integer, but in 2.5 the
+\function{id()} built-in was changed to always return non-negative
+numbers, and users often seem to use \code{id(self)} in
+\method{__hash__()} methods (though this is discouraged).
+% Bug #1536021
+
 \item ASCII is now the default encoding for modules.  It's now 
 a syntax error if a module contains string literals with 8-bit
 characters but doesn't have an encoding declaration.  In Python 2.4
@@ -1170,6 +1182,35 @@
 # -*- coding: latin1 -*-
 \end{verbatim}
 
+\item A new warning, \class{UnicodeWarning}, is triggered when 
+you attempt to compare a Unicode string and an 8-bit string 
+that can't be converted to Unicode using the default ASCII encoding.  
+The result of the comparison is false:
+
+\begin{verbatim}
+>>> chr(128) == unichr(128)   # Can't convert chr(128) to Unicode
+__main__:1: UnicodeWarning: Unicode equal comparison failed 
+  to convert both arguments to Unicode - interpreting them 
+  as being unequal
+False
+>>> chr(127) == unichr(127)   # chr(127) can be converted
+True
+\end{verbatim}
+
+Previously this would raise a \class{UnicodeDecodeError} exception,
+but in 2.5 this could result in puzzling problems when accessing a
+dictionary.  If you looked up \code{unichr(128)} and \code{chr(128)}
+was being used as a key, you'd get a \class{UnicodeDecodeError}
+exception.  Other changes in 2.5 resulted in this exception being
+raised instead of suppressed by the code in \file{dictobject.c} that
+implements dictionaries.
+
+Raising an exception for such a comparison is strictly correct, but
+the change might have broken code, so instead 
+\class{UnicodeWarning} was introduced.
+
+(Implemented by Marc-Andr\'e Lemburg.)
+
 \item One error that Python programmers sometimes make is forgetting
 to include an \file{__init__.py} module in a package directory.
 Debugging this mistake can be confusing, and usually requires running
@@ -1291,9 +1332,6 @@
 
 \end{itemize}
 
-The net result of the 2.5 optimizations is that Python 2.5 runs the
-pystone benchmark around XXX\% faster than Python 2.4.
-
 
 %======================================================================
 \section{New, Improved, and Removed Modules\label{modules}}
@@ -1489,6 +1527,29 @@
 
 (Contributed by Raymond Hettinger.)
 
+\item The \function{format()} function in the \module{locale} module
+has been modified and two new functions were added,
+\function{format_string()} and \function{currency()}.
+
+The \function{format()} function's \var{val} parameter could
+previously be a string as long as no more than one \%char specifier
+appeared; now the parameter must be exactly one \%char specifier with
+no surrounding text.  An optional \var{monetary} parameter was also
+added which, if \code{True}, will use the locale's rules for
+formatting currency in placing a separator between groups of three
+digits.
+
+To format strings with multiple \%char specifiers, use the new
+\function{format_string()} function that works like \function{format()}
+but also supports mixing \%char specifiers with
+arbitrary text.
+
+A new \function{currency()} function was also added that formats a
+number according to the current locale's settings.
+
+(Contributed by Georg Brandl.)
+% Patch 1180296
+
 \item The \module{mailbox} module underwent a massive rewrite to add
 the capability to modify mailboxes in addition to reading them.  A new
 set of classes that include \class{mbox}, \class{MH}, and
@@ -2214,13 +2275,20 @@
 carried out by Martin von~L\"owis.  The procedure was developed as
 \pep{347}.
 
+\item Coverity, a company that markets a source code analysis tool
+called Prevent, provided the results of their examination of the Python
+source code.  The analysis found about 60 bugs that 
+were quickly fixed.  Many of the bugs were refcounting problems, often
+occurring in error-handling code.  See
+\url{http://scan.coverity.com} for the statistics.
+
 \item The largest change to the C API came from \pep{353},
 which modifies the interpreter to use a \ctype{Py_ssize_t} type
 definition instead of \ctype{int}.  See the earlier
 section~\ref{pep-353} for a discussion of this change.
 
-\item The design of the bytecode compiler has changed a great deal, to
-no longer generate bytecode by traversing the parse tree.  Instead
+\item The design of the bytecode compiler has changed a great deal, 
+no longer generating bytecode by traversing the parse tree.  Instead
 the parse tree is converted to an abstract syntax tree (or AST), and it is 
 the abstract syntax tree that's traversed to produce the bytecode.
 
@@ -2261,6 +2329,32 @@
 Armin Rigo, and Neil Schemenauer, plus the participants in a number of
 AST sprints at conferences such as PyCon.
  
+\item Evan Jones's patch to obmalloc, first described in a talk
+at PyCon DC 2005, was applied.  Python 2.4 allocated small objects in
+256K-sized arenas, but never freed arenas.  With this patch, Python
+will free arenas when they're empty.  The net effect is that on some
+platforms, when you allocate many objects, Python's memory usage may
+actually drop when you delete them and the memory may be returned to
+the operating system.  (Implemented by Evan Jones, and reworked by Tim
+Peters.)
+
+Note that this change means extension modules must be more careful
+when allocating memory.  Python's API has many different
+functions for allocating memory that are grouped into families.  For
+example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
+\cfunction{PyMem_Free()} are one family that allocates raw memory,
+while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
+and \cfunction{PyObject_Free()} are another family that's supposed to
+be used for creating Python objects.  
+
+Previously these different families all reduced to the platform's
+\cfunction{malloc()} and \cfunction{free()} functions.  This meant 
+it didn't matter if you got things wrong and allocated memory with the
+\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
+function.  With 2.5's changes to obmalloc, these families now do different
+things and mismatches will probably result in a segfault.  You should
+carefully test your C extension modules with Python 2.5.
+
 \item The built-in set types now have an official C API.  Call
 \cfunction{PySet_New()} and \cfunction{PyFrozenSet_New()} to create a
 new set, \cfunction{PySet_Add()} and \cfunction{PySet_Discard()} to
@@ -2336,54 +2430,6 @@
 
 
 %======================================================================
-\section{Other Changes and Fixes \label{section-other}}
-
-As usual, there were a bunch of other improvements and bugfixes
-scattered throughout the source tree.  A search through the SVN change
-logs finds there were 334 patches applied and 443 bugs fixed between
-Python 2.4 and 2.5.  Both figures are likely to be underestimates.
-
-Some of the more notable changes are:
-
-\begin{itemize}
-
-\item Evan Jones's patch to obmalloc, first described in a talk
-at PyCon DC 2005, was applied.  Python 2.4 allocated small objects in
-256K-sized arenas, but never freed arenas.  With this patch, Python
-will free arenas when they're empty.  The net effect is that on some
-platforms, when you allocate many objects, Python's memory usage may
-actually drop when you delete them, and the memory may be returned to
-the operating system.  (Implemented by Evan Jones, and reworked by Tim
-Peters.)
-
-Note that this change means extension modules need to be more careful
-with how they allocate memory.  Python's API has many different
-functions for allocating memory that are grouped into families.  For
-example, \cfunction{PyMem_Malloc()}, \cfunction{PyMem_Realloc()}, and
-\cfunction{PyMem_Free()} are one family that allocates raw memory,
-while \cfunction{PyObject_Malloc()}, \cfunction{PyObject_Realloc()},
-and \cfunction{PyObject_Free()} are another family that's supposed to
-be used for creating Python objects.  
-
-Previously these different families all reduced to the platform's
-\cfunction{malloc()} and \cfunction{free()} functions.  This meant 
-it didn't matter if you got things wrong and allocated memory with the
-\cfunction{PyMem} function but freed it with the \cfunction{PyObject}
-function.  With the obmalloc change, these families now do different
-things, and mismatches will probably result in a segfault.  You should
-carefully test your C extension modules with Python 2.5.
-
-\item Coverity, a company that markets a source code analysis tool
-  called Prevent, provided the results of their examination of the Python
-  source code.  The analysis found about 60 bugs that 
-  were quickly fixed.  Many of the bugs were refcounting problems, often
-  occurring in error-handling code.  See
-  \url{http://scan.coverity.com} for the statistics.
-
-\end{itemize}
-
-
-%======================================================================
 \section{Porting to Python 2.5\label{porting}}
 
 This section lists previously described changes that may require
@@ -2401,11 +2447,22 @@
 described in section~\ref{pep-342}, it's now possible
 for \member{gi_frame} to be \code{None}.
 
+\item A new warning, \class{UnicodeWarning}, is triggered when 
+you attempt to compare a Unicode string and an 8-bit string that can't
+be converted to Unicode using the default ASCII encoding.  Previously
+such comparisons would raise a \class{UnicodeDecodeError} exception.
+
 \item Library: the \module{csv} module is now stricter about multi-line quoted
 fields.  If your files contain newlines embedded within fields, the
 input should be split into lines in a manner which preserves the
 newline characters.
 
+\item Library: the \module{locale} module's 
+\function{format()} function's would previously 
+accept any string as long as no more than one \%char specifier
+appeared.  In Python 2.5, the argument must be exactly one \%char
+specifier with no surrounding text. 
+
 \item Library: The \module{pickle} and \module{cPickle} modules no
 longer accept a return value of \code{None} from the
 \method{__reduce__()} method; the method must return a tuple of
@@ -2441,10 +2498,10 @@
 
 The author would like to thank the following people for offering
 suggestions, corrections and assistance with various drafts of this
-article: Nick Coghlan, Phillip J. Eby, Lars Gust\"abel, Raymond Hettinger, Ralf
-W. Grosse-Kunstleve, Kent Johnson, Martin von~L\"owis, Fredrik Lundh,
-Andrew McNamara, Skip Montanaro,
-Gustavo Niemeyer, James Pryor, Mike Rovner, Scott Weikart, Barry
-Warsaw, Thomas Wouters.
+article: Georg Brandl, Nick Coghlan, Phillip J. Eby, Lars Gust\"abel,
+Raymond Hettinger, Ralf W. Grosse-Kunstleve, Kent Johnson, Iain Lowe,
+Martin von~L\"owis, Fredrik Lundh, Andrew McNamara, Skip Montanaro,
+Gustavo Niemeyer, Paul Prescod, James Pryor, Mike Rovner, Scott
+Weikart, Barry Warsaw, Thomas Wouters.
 
 \end{document}

Modified: stackless/trunk/Include/abstract.h
==============================================================================
--- stackless/trunk/Include/abstract.h	(original)
+++ stackless/trunk/Include/abstract.h	Mon Aug 21 11:10:05 2006
@@ -758,13 +758,27 @@
 
        */
 
-     PyAPI_FUNC(Py_ssize_t) PyNumber_Index(PyObject *);
+#define PyIndex_Check(obj) \
+   ((obj)->ob_type->tp_as_number != NULL && \
+    PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_INDEX) && \
+    (obj)->ob_type->tp_as_number->nb_index != NULL)
+        
+     PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o);
 
        /*
-	 Returns the object converted to Py_ssize_t on success 
-	 or -1 with an error raised on failure.
+	 Returns the object converted to a Python long or int
+	 or NULL with an error raised on failure.
        */
 
+     PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc);
+
+       /*
+        Returns the object converted to Py_ssize_t by going through
+        PyNumber_Index first.  If an overflow error occurs while
+        converting the int-or-long to Py_ssize_t, then the second argument
+        is the error-type to return.  If it is NULL, then the overflow error
+        is cleared and the value is clipped. 
+       */
 
      PyAPI_FUNC(PyObject *) PyNumber_Int(PyObject *o);
 

Modified: stackless/trunk/Include/object.h
==============================================================================
--- stackless/trunk/Include/object.h	(original)
+++ stackless/trunk/Include/object.h	Mon Aug 21 11:10:05 2006
@@ -211,7 +211,7 @@
 	binaryfunc nb_inplace_true_divide;
 
 	/* Added in release 2.5 */
-	lenfunc nb_index;
+	unaryfunc nb_index;
 } PyNumberMethods;
 
 typedef struct {

Modified: stackless/trunk/Include/patchlevel.h
==============================================================================
--- stackless/trunk/Include/patchlevel.h	(original)
+++ stackless/trunk/Include/patchlevel.h	Mon Aug 21 11:10:05 2006
@@ -22,11 +22,11 @@
 #define PY_MAJOR_VERSION	2
 #define PY_MINOR_VERSION	5
 #define PY_MICRO_VERSION	0
-#define PY_RELEASE_LEVEL	PY_RELEASE_LEVEL_BETA
-#define PY_RELEASE_SERIAL	3
+#define PY_RELEASE_LEVEL	PY_RELEASE_LEVEL_GAMMA
+#define PY_RELEASE_SERIAL	1
 
 /* Version as a string */
-#define PY_VERSION		"2.5b3"
+#define PY_VERSION		"2.5c1"
 
 /* Subversion Revision number of this file (not of the repository) */
 #define PY_PATCHLEVEL_REVISION  "$Revision$"

Modified: stackless/trunk/Include/pyerrors.h
==============================================================================
--- stackless/trunk/Include/pyerrors.h	(original)
+++ stackless/trunk/Include/pyerrors.h	Mon Aug 21 11:10:05 2006
@@ -176,6 +176,7 @@
 PyAPI_DATA(PyObject *) PyExc_RuntimeWarning;
 PyAPI_DATA(PyObject *) PyExc_FutureWarning;
 PyAPI_DATA(PyObject *) PyExc_ImportWarning;
+PyAPI_DATA(PyObject *) PyExc_UnicodeWarning;
 
 
 /* Convenience functions */

Modified: stackless/trunk/Include/unicodeobject.h
==============================================================================
--- stackless/trunk/Include/unicodeobject.h	(original)
+++ stackless/trunk/Include/unicodeobject.h	Mon Aug 21 11:10:05 2006
@@ -189,6 +189,7 @@
 # define PyUnicode_RSplit PyUnicodeUCS2_RSplit
 # define PyUnicode_Replace PyUnicodeUCS2_Replace
 # define PyUnicode_Resize PyUnicodeUCS2_Resize
+# define PyUnicode_RichCompare PyUnicodeUCS2_RichCompare
 # define PyUnicode_SetDefaultEncoding PyUnicodeUCS2_SetDefaultEncoding
 # define PyUnicode_Split PyUnicodeUCS2_Split
 # define PyUnicode_Splitlines PyUnicodeUCS2_Splitlines
@@ -266,6 +267,7 @@
 # define PyUnicode_RSplit PyUnicodeUCS4_RSplit
 # define PyUnicode_Replace PyUnicodeUCS4_Replace
 # define PyUnicode_Resize PyUnicodeUCS4_Resize
+# define PyUnicode_RichCompare PyUnicodeUCS4_RichCompare
 # define PyUnicode_SetDefaultEncoding PyUnicodeUCS4_SetDefaultEncoding
 # define PyUnicode_Split PyUnicodeUCS4_Split
 # define PyUnicode_Splitlines PyUnicodeUCS4_Splitlines
@@ -1139,6 +1141,28 @@
     PyObject *right		/* Right string */
     );
 
+/* Rich compare two strings and return one of the following:
+
+   - NULL in case an exception was raised
+   - Py_True or Py_False for successfuly comparisons
+   - Py_NotImplemented in case the type combination is unknown
+
+   Note that Py_EQ and Py_NE comparisons can cause a UnicodeWarning in
+   case the conversion of the arguments to Unicode fails with a
+   UnicodeDecodeError.
+
+   Possible values for op:
+
+     Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE
+
+*/
+
+PyAPI_FUNC(PyObject *) PyUnicode_RichCompare(
+    PyObject *left,		/* Left string */ 
+    PyObject *right,		/* Right string */
+    int op			/* Operation: Py_EQ, Py_NE, Py_GT, etc. */
+    );
+
 /* Apply a argument tuple or dictionary to a format string and return
    the resulting Unicode string. */
 

Modified: stackless/trunk/Lib/Cookie.py
==============================================================================
--- stackless/trunk/Lib/Cookie.py	(original)
+++ stackless/trunk/Lib/Cookie.py	Mon Aug 21 11:10:05 2006
@@ -305,8 +305,10 @@
     '\375' : '\\375',  '\376' : '\\376',  '\377' : '\\377'
     }
 
+_idmap = ''.join(chr(x) for x in xrange(256))
+
 def _quote(str, LegalChars=_LegalChars,
-           idmap=string._idmap, translate=string.translate):
+           idmap=_idmap, translate=string.translate):
     #
     # If the string does not need to be double-quoted,
     # then just return the string.  Otherwise, surround
@@ -440,7 +442,7 @@
 
     def set(self, key, val, coded_val,
             LegalChars=_LegalChars,
-            idmap=string._idmap, translate=string.translate ):
+            idmap=_idmap, translate=string.translate):
         # First we verify that the key isn't a reserved word
         # Second we make sure it only contains legal characters
         if key.lower() in self._reserved:

Modified: stackless/trunk/Lib/cgi.py
==============================================================================
--- stackless/trunk/Lib/cgi.py	(original)
+++ stackless/trunk/Lib/cgi.py	Mon Aug 21 11:10:05 2006
@@ -251,6 +251,10 @@
 
     XXX This should really be subsumed by FieldStorage altogether -- no
     point in having two implementations of the same parsing algorithm.
+    Also, FieldStorage protects itself better against certain DoS attacks
+    by limiting the size of the data read in one chunk.  The API here
+    does not support that kind of protection.  This also affects parse()
+    since it can call parse_multipart().
 
     """
     boundary = ""
@@ -699,7 +703,7 @@
     def read_lines_to_eof(self):
         """Internal: read lines until EOF."""
         while 1:
-            line = self.fp.readline()
+            line = self.fp.readline(1<<16)
             if not line:
                 self.done = -1
                 break
@@ -710,12 +714,13 @@
         next = "--" + self.outerboundary
         last = next + "--"
         delim = ""
+        last_line_lfend = True
         while 1:
-            line = self.fp.readline()
+            line = self.fp.readline(1<<16)
             if not line:
                 self.done = -1
                 break
-            if line[:2] == "--":
+            if line[:2] == "--" and last_line_lfend:
                 strippedline = line.strip()
                 if strippedline == next:
                     break
@@ -726,11 +731,14 @@
             if line[-2:] == "\r\n":
                 delim = "\r\n"
                 line = line[:-2]
+                last_line_lfend = True
             elif line[-1] == "\n":
                 delim = "\n"
                 line = line[:-1]
+                last_line_lfend = True
             else:
                 delim = ""
+                last_line_lfend = False
             self.__write(odelim + line)
 
     def skip_lines(self):
@@ -739,18 +747,20 @@
             return
         next = "--" + self.outerboundary
         last = next + "--"
+        last_line_lfend = True
         while 1:
-            line = self.fp.readline()
+            line = self.fp.readline(1<<16)
             if not line:
                 self.done = -1
                 break
-            if line[:2] == "--":
+            if line[:2] == "--" and last_line_lfend:
                 strippedline = line.strip()
                 if strippedline == next:
                     break
                 if strippedline == last:
                     self.done = 1
                     break
+            last_line_lfend = line.endswith('\n')
 
     def make_file(self, binary=None):
         """Overridable: return a readable & writable file.

Modified: stackless/trunk/Lib/compiler/ast.py
==============================================================================
--- stackless/trunk/Lib/compiler/ast.py	(original)
+++ stackless/trunk/Lib/compiler/ast.py	Mon Aug 21 11:10:05 2006
@@ -583,11 +583,9 @@
     def __init__(self, code, lineno=None):
         self.code = code
         self.lineno = lineno
-        self.argnames = ['[outmost-iterable]']
+        self.argnames = ['.0']
         self.varargs = self.kwargs = None
 
-
-
     def getChildren(self):
         return self.code,
 

Modified: stackless/trunk/Lib/compiler/pycodegen.py
==============================================================================
--- stackless/trunk/Lib/compiler/pycodegen.py	(original)
+++ stackless/trunk/Lib/compiler/pycodegen.py	Mon Aug 21 11:10:05 2006
@@ -382,16 +382,7 @@
         self.set_lineno(node)
         for default in node.defaults:
             self.visit(default)
-        frees = gen.scope.get_free_vars()
-        if frees:
-            for name in frees:
-                self.emit('LOAD_CLOSURE', name)
-            self.emit('LOAD_CONST', gen)
-            self.emit('MAKE_CLOSURE', len(node.defaults))
-        else:
-            self.emit('LOAD_CONST', gen)
-            self.emit('MAKE_FUNCTION', len(node.defaults))
-
+        self._makeClosure(gen, len(node.defaults))
         for i in range(ndecorators):
             self.emit('CALL_FUNCTION', 1)
 
@@ -405,14 +396,7 @@
         for base in node.bases:
             self.visit(base)
         self.emit('BUILD_TUPLE', len(node.bases))
-        frees = gen.scope.get_free_vars()
-        for name in frees:
-            self.emit('LOAD_CLOSURE', name)
-        self.emit('LOAD_CONST', gen)
-        if frees:
-            self.emit('MAKE_CLOSURE', 0)
-        else:
-            self.emit('MAKE_FUNCTION', 0)
+        self._makeClosure(gen, 0)
         self.emit('CALL_FUNCTION', 0)
         self.emit('BUILD_CLASS')
         self.storeName(node.name)
@@ -644,22 +628,25 @@
         self.newBlock()
         self.emit('POP_TOP')
 
-    def visitGenExpr(self, node):
-        gen = GenExprCodeGenerator(node, self.scopes, self.class_name,
-                                   self.get_module())
-        walk(node.code, gen)
-        gen.finish()
-        self.set_lineno(node)
+    def _makeClosure(self, gen, args):
         frees = gen.scope.get_free_vars()
         if frees:
             for name in frees:
                 self.emit('LOAD_CLOSURE', name)
+            self.emit('BUILD_TUPLE', len(frees))
             self.emit('LOAD_CONST', gen)
-            self.emit('MAKE_CLOSURE', 0)
+            self.emit('MAKE_CLOSURE', args)
         else:
             self.emit('LOAD_CONST', gen)
-            self.emit('MAKE_FUNCTION', 0)
+            self.emit('MAKE_FUNCTION', args)
 
+    def visitGenExpr(self, node):
+        gen = GenExprCodeGenerator(node, self.scopes, self.class_name,
+                                   self.get_module())
+        walk(node.code, gen)
+        gen.finish()
+        self.set_lineno(node)
+        self._makeClosure(gen, 0)
         # precomputation of outmost iterable
         self.visit(node.code.quals[0].iter)
         self.emit('GET_ITER')
@@ -671,18 +658,19 @@
 
         stack = []
         for i, for_ in zip(range(len(node.quals)), node.quals):
-            start, anchor = self.visit(for_)
+            start, anchor, end = self.visit(for_)
             cont = None
             for if_ in for_.ifs:
                 if cont is None:
                     cont = self.newBlock()
                 self.visit(if_, cont)
-            stack.insert(0, (start, cont, anchor))
+            stack.insert(0, (start, cont, anchor, end))
 
         self.visit(node.expr)
         self.emit('YIELD_VALUE')
+        self.emit('POP_TOP')
 
-        for start, cont, anchor in stack:
+        for start, cont, anchor, end in stack:
             if cont:
                 skip_one = self.newBlock()
                 self.emit('JUMP_FORWARD', skip_one)
@@ -691,14 +679,22 @@
                 self.nextBlock(skip_one)
             self.emit('JUMP_ABSOLUTE', start)
             self.startBlock(anchor)
+            self.emit('POP_BLOCK')
+            self.setups.pop()
+            self.startBlock(end)
+
         self.emit('LOAD_CONST', None)
 
     def visitGenExprFor(self, node):
         start = self.newBlock()
         anchor = self.newBlock()
+        end = self.newBlock()
+
+        self.setups.push((LOOP, start))
+        self.emit('SETUP_LOOP', end)
 
         if node.is_outmost:
-            self.loadName('[outmost-iterable]')
+            self.loadName('.0')
         else:
             self.visit(node.iter)
             self.emit('GET_ITER')
@@ -708,7 +704,7 @@
         self.emit('FOR_ITER', anchor)
         self.nextBlock()
         self.visit(node.assign)
-        return start, anchor
+        return start, anchor, end
 
     def visitGenExprIf(self, node, branch):
         self.set_lineno(node, force=True)

Modified: stackless/trunk/Lib/compiler/symbols.py
==============================================================================
--- stackless/trunk/Lib/compiler/symbols.py	(original)
+++ stackless/trunk/Lib/compiler/symbols.py	Mon Aug 21 11:10:05 2006
@@ -188,7 +188,7 @@
         i = self.__counter
         self.__counter += 1
         self.__super_init("generator expression<%d>"%i, module, klass)
-        self.add_param('[outmost-iterable]')
+        self.add_param('.0')
 
     def get_names(self):
         keys = Scope.get_names(self)

Modified: stackless/trunk/Lib/ctypes/__init__.py
==============================================================================
--- stackless/trunk/Lib/ctypes/__init__.py	(original)
+++ stackless/trunk/Lib/ctypes/__init__.py	Mon Aug 21 11:10:05 2006
@@ -5,7 +5,7 @@
 
 import os as _os, sys as _sys
 
-__version__ = "1.0.0"
+__version__ = "1.0.1"
 
 from _ctypes import Union, Structure, Array
 from _ctypes import _Pointer
@@ -135,6 +135,11 @@
 
 class py_object(_SimpleCData):
     _type_ = "O"
+    def __repr__(self):
+        try:
+            return super(py_object, self).__repr__()
+        except ValueError:
+            return "%s(<NULL>)" % type(self).__name__
 
 class c_short(_SimpleCData):
     _type_ = "h"

Modified: stackless/trunk/Lib/ctypes/test/test_functions.py
==============================================================================
--- stackless/trunk/Lib/ctypes/test/test_functions.py	(original)
+++ stackless/trunk/Lib/ctypes/test/test_functions.py	Mon Aug 21 11:10:05 2006
@@ -222,6 +222,7 @@
 
         def callback(v):
             args.append(v)
+            return v
 
         CallBack = CFUNCTYPE(c_int, c_int)
 

Modified: stackless/trunk/Lib/ctypes/test/test_numbers.py
==============================================================================
--- stackless/trunk/Lib/ctypes/test/test_numbers.py	(original)
+++ stackless/trunk/Lib/ctypes/test/test_numbers.py	Mon Aug 21 11:10:05 2006
@@ -19,7 +19,7 @@
         result.append((min(a, b, c, d), max(a, b, c, d)))
     return result
 
-ArgType = type(c_int(0)._as_parameter_)
+ArgType = type(byref(c_int(0)))
 
 unsigned_types = [c_ubyte, c_ushort, c_uint, c_ulong]
 signed_types = [c_byte, c_short, c_int, c_long, c_longlong]
@@ -80,19 +80,6 @@
         for t in signed_types + unsigned_types + float_types:
             self.failUnlessEqual(ArgType, type(t.from_param(0)))
 
-    def test_as_parameter(self):
-        # The _as_parameter_ property must also
-        # be a PyCArgObject instance
-        for t in signed_types + unsigned_types + float_types:
-            parm = t()._as_parameter_
-            self.failUnlessEqual(ArgType, type(parm))
-
-            # _as_parameter_ is readonly!
-            #
-            # Python 2.3 and 2.4 raise a TypeError when trying to set
-            # a readonly attribute, 2.5 raises an AttributeError.
-            self.assertRaises((AttributeError, TypeError), setattr, t(), "_as_parameter_", None)
-
     def test_byref(self):
         # calling byref returns also a PyCArgObject instance
         for t in signed_types + unsigned_types + float_types:

Modified: stackless/trunk/Lib/ctypes/test/test_prototypes.py
==============================================================================
--- stackless/trunk/Lib/ctypes/test/test_prototypes.py	(original)
+++ stackless/trunk/Lib/ctypes/test/test_prototypes.py	Mon Aug 21 11:10:05 2006
@@ -125,13 +125,18 @@
             self.failUnlessEqual(None, func(c_wchar_p(None)))
             self.failUnlessEqual(u"123", func(c_wchar_p(u"123")))
 
-##    def test_instance(self):
-##        func = testdll._testfunc_p_p
+    def test_instance(self):
+        func = testdll._testfunc_p_p
+        func.restype = c_void_p
 
-##        class X:
-##            _as_parameter_ = 0
+        class X:
+            _as_parameter_ = None
 
-##        self.failUnlessEqual(0, func(X()))
+        func.argtypes = c_void_p,
+        self.failUnlessEqual(None, func(X()))
+
+        func.argtypes = None
+        self.failUnlessEqual(None, func(X()))
 
 try:
     c_wchar

Modified: stackless/trunk/Lib/ctypes/test/test_python_api.py
==============================================================================
--- stackless/trunk/Lib/ctypes/test/test_python_api.py	(original)
+++ stackless/trunk/Lib/ctypes/test/test_python_api.py	Mon Aug 21 11:10:05 2006
@@ -78,5 +78,10 @@
         # not enough arguments
         self.failUnlessRaises(TypeError, PyOS_snprintf, buf)
 
+    def test_pyobject_repr(self):
+        self.failUnlessEqual(repr(py_object()), "py_object(<NULL>)")
+        self.failUnlessEqual(repr(py_object(42)), "py_object(42)")
+        self.failUnlessEqual(repr(py_object(object)), "py_object(%r)" % object)
+
 if __name__ == "__main__":
     unittest.main()

Modified: stackless/trunk/Lib/distutils/__init__.py
==============================================================================
--- stackless/trunk/Lib/distutils/__init__.py	(original)
+++ stackless/trunk/Lib/distutils/__init__.py	Mon Aug 21 11:10:05 2006
@@ -12,6 +12,12 @@
 
 __revision__ = "$Id$"
 
-import sys
-__version__ = "%d.%d.%d" % sys.version_info[:3]
-del sys
+# Distutils version
+#
+# Please coordinate with Marc-Andre Lemburg <mal at egenix.com> when adding
+# new features to distutils that would warrant bumping the version number.
+#
+# In general, major and minor version should loosely follow the Python
+# version number the distutils code was shipped with.
+#
+__version__ = "2.5.0"

Modified: stackless/trunk/Lib/idlelib/Bindings.py
==============================================================================
--- stackless/trunk/Lib/idlelib/Bindings.py	(original)
+++ stackless/trunk/Lib/idlelib/Bindings.py	Mon Aug 21 11:10:05 2006
@@ -22,9 +22,9 @@
    None,
    ('_Save', '<<save-window>>'),
    ('Save _As...', '<<save-window-as-file>>'),
-   ('Save Co_py As...', '<<save-copy-of-window-as-file>>'),
+   ('Save Cop_y As...', '<<save-copy-of-window-as-file>>'),
    None,
-   ('_Print Window', '<<print-window>>'),
+   ('Prin_t Window', '<<print-window>>'),
    None,
    ('_Close', '<<close-window>>'),
    ('E_xit', '<<close-all-windows>>'),

Modified: stackless/trunk/Lib/idlelib/CREDITS.txt
==============================================================================
--- stackless/trunk/Lib/idlelib/CREDITS.txt	(original)
+++ stackless/trunk/Lib/idlelib/CREDITS.txt	Mon Aug 21 11:10:05 2006
@@ -19,13 +19,13 @@
 subprocess, and made a number of usability enhancements.
 
 Other contributors include Raymond Hettinger, Tony Lownds (Mac integration),
-Neal Norwitz (code check and clean-up), Noam Raphael (Code Context, Call Tips,
-many other patches), and Chui Tey (RPC integration, debugger integration and
-persistent breakpoints).
+Neal Norwitz (code check and clean-up), Ronald Oussoren (Mac integration),
+Noam Raphael (Code Context, Call Tips, many other patches), and Chui Tey (RPC
+integration, debugger integration and persistent breakpoints).
 
 Scott David Daniels, Tal Einat, Hernan Foffani, Christos Georgiou,
-Martin v. Löwis, Jason Orendorff, Josh Robb, Nigel Rowe, Bruce Sherwood,
-and Jeff Shute have submitted useful patches.  Thanks, guys!
+Jim Jewett, Martin v. Löwis, Jason Orendorff, Josh Robb, Nigel Rowe,
+Bruce Sherwood, and Jeff Shute have submitted useful patches.  Thanks, guys!
 
 For additional details refer to NEWS.txt and Changelog.
 

Modified: stackless/trunk/Lib/idlelib/CodeContext.py
==============================================================================
--- stackless/trunk/Lib/idlelib/CodeContext.py	(original)
+++ stackless/trunk/Lib/idlelib/CodeContext.py	Mon Aug 21 11:10:05 2006
@@ -15,7 +15,7 @@
 from sys import maxint as INFINITY
 
 BLOCKOPENERS = set(["class", "def", "elif", "else", "except", "finally", "for",
-                    "if", "try", "while"])
+                    "if", "try", "while", "with"])
 UPDATEINTERVAL = 100 # millisec
 FONTUPDATEINTERVAL = 1000 # millisec
 

Modified: stackless/trunk/Lib/idlelib/EditorWindow.py
==============================================================================
--- stackless/trunk/Lib/idlelib/EditorWindow.py	(original)
+++ stackless/trunk/Lib/idlelib/EditorWindow.py	Mon Aug 21 11:10:05 2006
@@ -1277,13 +1277,13 @@
               "Toggle tabs",
               "Turn tabs " + ("on", "off")[self.usetabs] +
               "?\nIndent width " +
-              ("will be", "remains at")[self.usetabs] + " 8.",
+              ("will be", "remains at")[self.usetabs] + " 8." +
+              "\n Note: a tab is always 8 columns",
               parent=self.text):
             self.usetabs = not self.usetabs
-        # Try to prevent mixed tabs/spaces.
-        # User must reset indent width manually after using tabs
-        #      if he insists on getting into trouble.
-        self.indentwidth = 8
+            # Try to prevent inconsistent indentation.
+            # User must change indent width manually after using tabs.
+            self.indentwidth = 8
         return "break"
 
     # XXX this isn't bound to anything -- see tabwidth comments

Modified: stackless/trunk/Lib/idlelib/NEWS.txt
==============================================================================
--- stackless/trunk/Lib/idlelib/NEWS.txt	(original)
+++ stackless/trunk/Lib/idlelib/NEWS.txt	Mon Aug 21 11:10:05 2006
@@ -1,3 +1,28 @@
+What's New in IDLE 1.2c1?
+=========================
+
+*Release date: 17-AUG-2006*
+
+- File menu hotkeys: there were three 'p' assignments.  Reassign the
+  'Save Copy As' and 'Print' hotkeys to 'y' and 't'.  Change the
+  Shell hotkey from 's' to 'l'.
+
+- IDLE honors new quit() and exit() commands from site.py Quitter() object.
+  Patch 1540892, Jim Jewett
+
+- The 'with' statement is now a Code Context block opener.
+  Patch 1540851, Jim Jewett
+
+- Retrieval of previous shell command was not always preserving indentation
+  (since 1.2a1) Patch 1528468 Tal Einat.
+
+- Changing tokenize (39046) to detect dedent broke tabnanny check (since 1.2a1)
+
+- ToggleTab dialog was setting indent to 8 even if cancelled (since 1.2a1).
+
+- When used w/o subprocess, all exceptions were preceded by an error
+  message claiming they were IDLE internal errors (since 1.2a1).
+
 What's New in IDLE 1.2b3?
 =========================
 

Modified: stackless/trunk/Lib/idlelib/PyShell.py
==============================================================================
--- stackless/trunk/Lib/idlelib/PyShell.py	(original)
+++ stackless/trunk/Lib/idlelib/PyShell.py	Mon Aug 21 11:10:05 2006
@@ -478,9 +478,6 @@
         import sys as _sys
         _sys.path = %r
         del _sys
-        _msg = 'Use File/Exit or your end-of-file key to quit IDLE'
-        __builtins__.quit = __builtins__.exit = _msg
-        del _msg
         \n""" % (sys.path,))
 
     active_seq = None
@@ -514,7 +511,10 @@
                 print >>sys.__stderr__, errmsg, what
                 print >>console, errmsg, what
             # we received a response to the currently active seq number:
-            self.tkconsole.endexecuting()
+            try:
+                self.tkconsole.endexecuting()
+            except AttributeError:  # shell may have closed
+                pass
         # Reschedule myself
         if not self.tkconsole.closing:
             self.tkconsole.text.after(self.tkconsole.pollinterval,
@@ -593,7 +593,7 @@
                 source = source.encode(IOBinding.encoding)
             except UnicodeError:
                 self.tkconsole.resetoutput()
-                self.write("Unsupported characters in input")
+                self.write("Unsupported characters in input\n")
                 return
         try:
             # InteractiveInterpreter.runsource() calls its runcode() method,
@@ -713,20 +713,30 @@
                 else:
                     exec code in self.locals
             except SystemExit:
-                if tkMessageBox.askyesno(
-                    "Exit?",
-                    "Do you want to exit altogether?",
-                    default="yes",
-                    master=self.tkconsole.text):
-                    raise
+                if not self.tkconsole.closing:
+                    if tkMessageBox.askyesno(
+                        "Exit?",
+                        "Do you want to exit altogether?",
+                        default="yes",
+                        master=self.tkconsole.text):
+                        raise
+                    else:
+                        self.showtraceback()
                 else:
-                    self.showtraceback()
+                    raise
             except:
-                print>>sys.stderr, "IDLE internal error in runcode()"
+                if use_subprocess:
+                    print >> self.tkconsole.stderr, \
+                             "IDLE internal error in runcode()"
                 self.showtraceback()
+                if use_subprocess:
+                    self.tkconsole.endexecuting()
         finally:
             if not use_subprocess:
-                self.tkconsole.endexecuting()
+                try:
+                    self.tkconsole.endexecuting()
+                except AttributeError:  # shell may have closed
+                    pass
 
     def write(self, s):
         "Override base class method"
@@ -790,7 +800,7 @@
         if use_subprocess:
             ms = self.menu_specs
             if ms[2][0] != "shell":
-                ms.insert(2, ("shell", "_Shell"))
+                ms.insert(2, ("shell", "She_ll"))
         self.interp = ModifiedInterpreter(self)
         if flist is None:
             root = Tk()
@@ -800,9 +810,6 @@
         #
         OutputWindow.__init__(self, flist, None, None)
         #
-        import __builtin__
-        __builtin__.quit = __builtin__.exit = "To exit, type Ctrl-D."
-        #
 ##        self.config(usetabs=1, indentwidth=8, context_use_ps1=1)
         self.usetabs = True
         # indentwidth must be 8 when using tabs.  See note in EditorWindow:
@@ -1134,21 +1141,27 @@
         return "break"
 
     def recall(self, s, event):
+        # remove leading and trailing empty or whitespace lines
+        s = re.sub(r'^\s*\n', '' , s)
+        s = re.sub(r'\n\s*$', '', s)
+        lines = s.split('\n')
         self.text.undo_block_start()
         try:
             self.text.tag_remove("sel", "1.0", "end")
             self.text.mark_set("insert", "end-1c")
-            s = s.strip()
-            lines = s.split('\n')
-            prefix = self.text.get("insert linestart","insert").rstrip()
-            if prefix and prefix[-1]==':':
+            prefix = self.text.get("insert linestart", "insert")
+            if prefix.rstrip().endswith(':'):
                 self.newline_and_indent_event(event)
-            self.text.insert("insert",lines[0].strip())
+                prefix = self.text.get("insert linestart", "insert")
+            self.text.insert("insert", lines[0].strip())
             if len(lines) > 1:
-                self.newline_and_indent_event(event)
+                orig_base_indent = re.search(r'^([ \t]*)', lines[0]).group(0)
+                new_base_indent  = re.search(r'^([ \t]*)', prefix).group(0)
                 for line in lines[1:]:
-                    self.text.insert("insert", line.strip())
-                    self.newline_and_indent_event(event)
+                    if line.startswith(orig_base_indent):
+                        # replace orig base indentation with new indentation
+                        line = new_base_indent + line[len(orig_base_indent):]
+                    self.text.insert('insert', '\n'+line.rstrip())
         finally:
             self.text.see("insert")
             self.text.undo_block_stop()

Modified: stackless/trunk/Lib/idlelib/ScriptBinding.py
==============================================================================
--- stackless/trunk/Lib/idlelib/ScriptBinding.py	(original)
+++ stackless/trunk/Lib/idlelib/ScriptBinding.py	Mon Aug 21 11:10:05 2006
@@ -76,6 +76,9 @@
             self.editwin.gotoline(nag.get_lineno())
             self.errorbox("Tab/space error", indent_message)
             return False
+        except IndentationError:
+            # From tokenize(), let compile() in checksyntax find it again.
+            pass
         return True
 
     def checksyntax(self, filename):

Modified: stackless/trunk/Lib/idlelib/idlever.py
==============================================================================
--- stackless/trunk/Lib/idlelib/idlever.py	(original)
+++ stackless/trunk/Lib/idlelib/idlever.py	Mon Aug 21 11:10:05 2006
@@ -1 +1 @@
-IDLE_VERSION = "1.2b3"
+IDLE_VERSION = "1.2c1"

Modified: stackless/trunk/Lib/logging/__init__.py
==============================================================================
--- stackless/trunk/Lib/logging/__init__.py	(original)
+++ stackless/trunk/Lib/logging/__init__.py	Mon Aug 21 11:10:05 2006
@@ -1337,14 +1337,14 @@
     """
     root.manager.disable = level
 
-def shutdown():
+def shutdown(handlerList=_handlerList):
     """
     Perform any cleanup actions in the logging system (e.g. flushing
     buffers).
 
     Should be called at application exit.
     """
-    for h in _handlerList[:]: # was _handlers.keys():
+    for h in handlerList[:]:
         #errors might occur, for example, if files are locked
         #we just ignore them if raiseExceptions is not set
         try:

Modified: stackless/trunk/Lib/logging/config.py
==============================================================================
--- stackless/trunk/Lib/logging/config.py	(original)
+++ stackless/trunk/Lib/logging/config.py	Mon Aug 21 11:10:05 2006
@@ -79,7 +79,7 @@
     logging._acquireLock()
     try:
         logging._handlers.clear()
-        logging._handlerList = []
+        del logging._handlerList[:]
         # Handlers add themselves to logging._handlers
         handlers = _install_handlers(cp, formatters)
         _install_loggers(cp, handlers)

Modified: stackless/trunk/Lib/site.py
==============================================================================
--- stackless/trunk/Lib/site.py	(original)
+++ stackless/trunk/Lib/site.py	Mon Aug 21 11:10:05 2006
@@ -27,7 +27,7 @@
 '#' are skipped. Lines starting with 'import' are executed.
 
 For example, suppose sys.prefix and sys.exec_prefix are set to
-/usr/local and there is a directory /usr/local/lib/python1.5/site-packages
+/usr/local and there is a directory /usr/local/lib/python2.5/site-packages
 with three subdirectories, foo, bar and spam, and two path
 configuration files, foo.pth and bar.pth.  Assume foo.pth contains the
 following:
@@ -44,8 +44,8 @@
 
 Then the following directories are added to sys.path, in this order:
 
-  /usr/local/lib/python1.5/site-packages/bar
-  /usr/local/lib/python1.5/site-packages/foo
+  /usr/local/lib/python2.5/site-packages/bar
+  /usr/local/lib/python2.5/site-packages/foo
 
 Note that bletch is omitted because it doesn't exist; bar precedes foo
 because bar.pth comes alphabetically before foo.pth; and spam is
@@ -242,6 +242,12 @@
         def __repr__(self):
             return 'Use %s() or %s to exit' % (self.name, eof)
         def __call__(self, code=None):
+            # Shells like IDLE catch the SystemExit, but listen when their
+            # stdin wrapper is closed.
+            try:
+                sys.stdin.close()
+            except:
+                pass
             raise SystemExit(code)
     __builtin__.quit = Quitter('quit')
     __builtin__.exit = Quitter('exit')

Modified: stackless/trunk/Lib/string.py
==============================================================================
--- stackless/trunk/Lib/string.py	(original)
+++ stackless/trunk/Lib/string.py	Mon Aug 21 11:10:05 2006
@@ -35,7 +35,6 @@
 
 # Case conversion helpers
 # Use str to convert Unicode literal in case of -U
-# Note that Cookie.py bogusly uses _idmap :(
 l = map(chr, xrange(256))
 _idmap = str('').join(l)
 del l

Modified: stackless/trunk/Lib/tabnanny.py
==============================================================================
--- stackless/trunk/Lib/tabnanny.py	(original)
+++ stackless/trunk/Lib/tabnanny.py	Mon Aug 21 11:10:05 2006
@@ -109,6 +109,10 @@
         errprint("%r: Token Error: %s" % (file, msg))
         return
 
+    except IndentationError, msg:
+        errprint("%r: Indentation Error: %s" % (file, msg))
+        return
+
     except NannyNag, nag:
         badline = nag.get_lineno()
         line = nag.get_line()

Modified: stackless/trunk/Lib/test/exception_hierarchy.txt
==============================================================================
--- stackless/trunk/Lib/test/exception_hierarchy.txt	(original)
+++ stackless/trunk/Lib/test/exception_hierarchy.txt	Mon Aug 21 11:10:05 2006
@@ -46,3 +46,4 @@
            +-- UserWarning
            +-- FutureWarning
 	   +-- ImportWarning
+	   +-- UnicodeWarning

Modified: stackless/trunk/Lib/test/inspect_fodder2.py
==============================================================================
--- stackless/trunk/Lib/test/inspect_fodder2.py	(original)
+++ stackless/trunk/Lib/test/inspect_fodder2.py	Mon Aug 21 11:10:05 2006
@@ -88,3 +88,12 @@
 def func88():
     # comment
     return 90
+
+# line 92
+def f():
+    class X:
+        def g():
+            "doc"
+            return 42
+    return X
+method_in_dynamic_class = f().g.im_func

Modified: stackless/trunk/Lib/test/output/test_cgi
==============================================================================
--- stackless/trunk/Lib/test/output/test_cgi	(original)
+++ stackless/trunk/Lib/test/output/test_cgi	Mon Aug 21 11:10:05 2006
@@ -38,3 +38,5 @@
 Testing log
 Testing initlog 1
 Testing log 2
+Test FieldStorage methods that use readline
+Test basic FieldStorage multipart parsing

Modified: stackless/trunk/Lib/test/regrtest.py
==============================================================================
--- stackless/trunk/Lib/test/regrtest.py	(original)
+++ stackless/trunk/Lib/test/regrtest.py	Mon Aug 21 11:10:05 2006
@@ -66,7 +66,9 @@
 
 -M runs tests that require an exorbitant amount of memory. These tests
 typically try to ascertain containers keep working when containing more than
-2 bilion objects, and only work on 64-bit systems. The passed-in memlimit,
+2 billion objects, which only works on 64-bit systems. There are also some
+tests that try to exhaust the address space of the process, which only makes
+sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit,
 which is a string in the form of '2.5Gb', determines howmuch memory the
 tests will limit themselves to (but they may go slightly over.) The number
 shouldn't be more memory than the machine has (including swap memory). You

Modified: stackless/trunk/Lib/test/test_builtin.py
==============================================================================
--- stackless/trunk/Lib/test/test_builtin.py	(original)
+++ stackless/trunk/Lib/test/test_builtin.py	Mon Aug 21 11:10:05 2006
@@ -640,6 +640,19 @@
         def f(): pass
         self.assertRaises(TypeError, hash, [])
         self.assertRaises(TypeError, hash, {})
+        # Bug 1536021: Allow hash to return long objects
+        class X:
+            def __hash__(self):
+                return 2**100
+        self.assertEquals(type(hash(X())), int)
+        class Y(object):
+            def __hash__(self):
+                return 2**100
+        self.assertEquals(type(hash(Y())), int)
+        class Z(long):
+            def __hash__(self):
+                return self
+        self.assertEquals(hash(Z(42)), hash(42L))
 
     def test_hex(self):
         self.assertEqual(hex(16), '0x10')
@@ -1432,6 +1445,14 @@
             self.assertEqual(input('testing\n'), 2)
             self.assertEqual(raw_input(), 'The quick brown fox jumps over the lazy dog.')
             self.assertEqual(raw_input('testing\n'), 'Dear John')
+
+            # SF 1535165: don't segfault on closed stdin
+            # sys.stdout must be a regular file for triggering
+            sys.stdout = savestdout
+            sys.stdin.close()
+            self.assertRaises(ValueError, input)
+
+            sys.stdout = BitBucket()
             sys.stdin = cStringIO.StringIO("NULL\0")
             self.assertRaises(TypeError, input, 42, 42)
             sys.stdin = cStringIO.StringIO("    'whitespace'")

Modified: stackless/trunk/Lib/test/test_bz2.py
==============================================================================
--- stackless/trunk/Lib/test/test_bz2.py	(original)
+++ stackless/trunk/Lib/test/test_bz2.py	Mon Aug 21 11:10:05 2006
@@ -166,10 +166,21 @@
         sio = StringIO(self.TEXT)
         bz2f.writelines(sio.readlines())
         bz2f.close()
+        # patch #1535500
+        self.assertRaises(ValueError, bz2f.writelines, ["a"])
         f = open(self.filename, 'rb')
         self.assertEqual(self.decompress(f.read()), self.TEXT)
         f.close()
 
+    def testWriteMethodsOnReadOnlyFile(self):
+        bz2f = BZ2File(self.filename, "w")
+        bz2f.write("abc")
+        bz2f.close()
+
+        bz2f = BZ2File(self.filename, "r")
+        self.assertRaises(IOError, bz2f.write, "a")
+        self.assertRaises(IOError, bz2f.writelines, ["a"])
+
     def testSeekForward(self):
         # "Test BZ2File.seek(150, 0)"
         self.createTempFile()
@@ -258,7 +269,7 @@
         bz2f = BZ2File(self.filename)
         xlines = list(bz2f.xreadlines())
         bz2f.close()
-        self.assertEqual(lines, ['Test'])
+        self.assertEqual(xlines, ['Test'])
 
 
 class BZ2CompressorTest(BaseTest):

Modified: stackless/trunk/Lib/test/test_cgi.py
==============================================================================
--- stackless/trunk/Lib/test/test_cgi.py	(original)
+++ stackless/trunk/Lib/test/test_cgi.py	Mon Aug 21 11:10:05 2006
@@ -2,6 +2,8 @@
 import cgi
 import os
 import sys
+import tempfile
+from StringIO import StringIO
 
 class HackedSysModule:
     # The regression test will have real values in sys.argv, which
@@ -203,4 +205,71 @@
         cgi.initlog("%s", "Testing log 3")
         cgi.log("Testing log 4")
 
+    print "Test FieldStorage methods that use readline"
+    # FieldStorage uses readline, which has the capacity to read all
+    # contents of the input file into memory; we use readline's size argument
+    # to prevent that for files that do not contain any newlines in
+    # non-GET/HEAD requests
+    class TestReadlineFile:
+        def __init__(self, file):
+            self.file = file
+            self.numcalls = 0
+
+        def readline(self, size=None):
+            self.numcalls += 1
+            if size:
+                return self.file.readline(size)
+            else:
+                return self.file.readline()
+
+        def __getattr__(self, name):
+            file = self.__dict__['file']
+            a = getattr(file, name)
+            if not isinstance(a, int):
+                setattr(self, name, a)
+            return a
+
+    f = TestReadlineFile(tempfile.TemporaryFile())
+    f.write('x' * 256 * 1024)
+    f.seek(0)
+    env = {'REQUEST_METHOD':'PUT'}
+    fs = cgi.FieldStorage(fp=f, environ=env)
+    # if we're not chunking properly, readline is only called twice
+    # (by read_binary); if we are chunking properly, it will be called 5 times
+    # as long as the chunksize is 1 << 16.
+    verify(f.numcalls > 2)
+
+    print "Test basic FieldStorage multipart parsing"
+    env = {'REQUEST_METHOD':'POST', 'CONTENT_TYPE':'multipart/form-data; boundary=---------------------------721837373350705526688164684', 'CONTENT_LENGTH':'558'}
+    postdata = """-----------------------------721837373350705526688164684
+Content-Disposition: form-data; name="id"
+
+1234
+-----------------------------721837373350705526688164684
+Content-Disposition: form-data; name="title"
+
+
+-----------------------------721837373350705526688164684
+Content-Disposition: form-data; name="file"; filename="test.txt"
+Content-Type: text/plain
+
+Testing 123.
+
+-----------------------------721837373350705526688164684
+Content-Disposition: form-data; name="submit"
+
+ Add\x20
+-----------------------------721837373350705526688164684--
+"""
+    fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env)
+    verify(len(fs.list) == 4)
+    expect = [{'name':'id', 'filename':None, 'value':'1234'},
+              {'name':'title', 'filename':None, 'value':''},
+              {'name':'file', 'filename':'test.txt','value':'Testing 123.\n'},
+              {'name':'submit', 'filename':None, 'value':' Add '}]
+    for x in range(len(fs.list)):
+        for k, exp in expect[x].items():
+            got = getattr(fs.list[x], k)
+            verify(got == exp)
+
 main()

Modified: stackless/trunk/Lib/test/test_code.py
==============================================================================
--- stackless/trunk/Lib/test/test_code.py	(original)
+++ stackless/trunk/Lib/test/test_code.py	Mon Aug 21 11:10:05 2006
@@ -61,6 +61,23 @@
 flags: 67
 consts: ('None',)
 
+>>> def optimize_away():
+...     'doc string'
+...     'not a docstring'
+...     53
+...     53L
+
+>>> dump(optimize_away.func_code)
+name: optimize_away
+argcount: 0
+names: ()
+varnames: ()
+cellvars: ()
+freevars: ()
+nlocals: 0
+flags: 67
+consts: ("'doc string'", 'None')
+
 """
 
 def consts(t):

Modified: stackless/trunk/Lib/test/test_compiler.py
==============================================================================
--- stackless/trunk/Lib/test/test_compiler.py	(original)
+++ stackless/trunk/Lib/test/test_compiler.py	Mon Aug 21 11:10:05 2006
@@ -104,6 +104,26 @@
         self.assertEquals(flatten([1, [2]]), [1, 2])
         self.assertEquals(flatten((1, (2,))), [1, 2])
 
+    def testNestedScope(self):
+        c = compiler.compile('def g():\n'
+                             '    a = 1\n'
+                             '    def f(): return a + 2\n'
+                             '    return f()\n'
+                             'result = g()',
+                             '<string>',
+                             'exec')
+        dct = {}
+        exec c in dct
+        self.assertEquals(dct.get('result'), 3)
+
+    def testGenExp(self):
+        c = compiler.compile('list((i,j) for i in range(3) if i < 3'
+                             '           for j in range(4) if j > 2)',
+                             '<string>',
+                             'eval')
+        self.assertEquals(eval(c), [(0, 3), (1, 3), (2, 3)])
+
+
 NOLINENO = (compiler.ast.Module, compiler.ast.Stmt, compiler.ast.Discard)
 
 ###############################################################################

Modified: stackless/trunk/Lib/test/test_descr.py
==============================================================================
--- stackless/trunk/Lib/test/test_descr.py	(original)
+++ stackless/trunk/Lib/test/test_descr.py	Mon Aug 21 11:10:05 2006
@@ -2024,6 +2024,16 @@
         prop2 = property(fset=setter)
         vereq(prop2.__doc__, None)
 
+    # this segfaulted in 2.5b2
+    try:
+        import _testcapi
+    except ImportError:
+        pass
+    else:
+        class X(object):
+            p = property(_testcapi.test_with_docstring)
+
+
 def supers():
     if verbose: print "Testing super..."
 

Modified: stackless/trunk/Lib/test/test_format.py
==============================================================================
--- stackless/trunk/Lib/test/test_format.py	(original)
+++ stackless/trunk/Lib/test/test_format.py	Mon Aug 21 11:10:05 2006
@@ -230,6 +230,14 @@
 test_exc(u'no format', u'1', TypeError,
          "not all arguments converted during string formatting")
 
+class Foobar(long):
+    def __oct__(self):
+        # Returning a non-string should not blow up.
+        return self + 1
+
+test_exc('%o', Foobar(), TypeError,
+         "expected string or Unicode object, long found")
+
 if sys.maxint == 2**31-1:
     # crashes 2.2.1 and earlier:
     try:

Modified: stackless/trunk/Lib/test/test_index.py
==============================================================================
--- stackless/trunk/Lib/test/test_index.py	(original)
+++ stackless/trunk/Lib/test/test_index.py	Mon Aug 21 11:10:05 2006
@@ -1,6 +1,7 @@
 import unittest
 from test import test_support
 import operator
+from sys import maxint
 
 class oldstyle:
     def __index__(self):
@@ -10,68 +11,116 @@
     def __index__(self):
         return self.ind
 
+class TrapInt(int):
+    def __index__(self):
+        return self
+
+class TrapLong(long):
+    def __index__(self):
+        return self
+
 class BaseTestCase(unittest.TestCase):
     def setUp(self):
         self.o = oldstyle()
         self.n = newstyle()
-        self.o2 = oldstyle()
-        self.n2 = newstyle()
 
     def test_basic(self):
         self.o.ind = -2
         self.n.ind = 2
-        assert(self.seq[self.n] == self.seq[2])
-        assert(self.seq[self.o] == self.seq[-2])
-        assert(operator.index(self.o) == -2)
-        assert(operator.index(self.n) == 2)
+        self.assertEqual(operator.index(self.o), -2)
+        self.assertEqual(operator.index(self.n), 2)
+
+    def test_slice(self):
+        self.o.ind = 1
+        self.n.ind = 2
+        slc = slice(self.o, self.o, self.o)
+        check_slc = slice(1, 1, 1)
+        self.assertEqual(slc.indices(self.o), check_slc.indices(1))
+        slc = slice(self.n, self.n, self.n)
+        check_slc = slice(2, 2, 2)
+        self.assertEqual(slc.indices(self.n), check_slc.indices(2))
+
+    def test_wrappers(self):
+        self.o.ind = 4
+        self.n.ind = 5
+        self.assertEqual(6 .__index__(), 6)
+        self.assertEqual(-7L.__index__(), -7)
+        self.assertEqual(self.o.__index__(), 4)
+        self.assertEqual(self.n.__index__(), 5)
+
+    def test_subclasses(self):
+        r = range(10)
+        self.assertEqual(r[TrapInt(5):TrapInt(10)], r[5:10])
+        self.assertEqual(r[TrapLong(5):TrapLong(10)], r[5:10])
+        self.assertEqual(slice(TrapInt()).indices(0), (0,0,1))
+        self.assertEqual(slice(TrapLong(0)).indices(0), (0,0,1))
 
     def test_error(self):
         self.o.ind = 'dumb'
         self.n.ind = 'bad'
-        myfunc = lambda x, obj: obj.seq[x]
         self.failUnlessRaises(TypeError, operator.index, self.o)
         self.failUnlessRaises(TypeError, operator.index, self.n)
-        self.failUnlessRaises(TypeError, myfunc, self.o, self)
-        self.failUnlessRaises(TypeError, myfunc, self.n, self)
+        self.failUnlessRaises(TypeError, slice(self.o).indices, 0)
+        self.failUnlessRaises(TypeError, slice(self.n).indices, 0)
+
+
+class SeqTestCase(unittest.TestCase):
+    # This test case isn't run directly. It just defines common tests
+    # to the different sequence types below
+    def setUp(self):
+        self.o = oldstyle()
+        self.n = newstyle()
+        self.o2 = oldstyle()
+        self.n2 = newstyle()
+
+    def test_index(self):
+        self.o.ind = -2
+        self.n.ind = 2
+        self.assertEqual(self.seq[self.n], self.seq[2])
+        self.assertEqual(self.seq[self.o], self.seq[-2])
 
     def test_slice(self):
         self.o.ind = 1
         self.o2.ind = 3
         self.n.ind = 2
         self.n2.ind = 4
-        assert(self.seq[self.o:self.o2] == self.seq[1:3])
-        assert(self.seq[self.n:self.n2] == self.seq[2:4])
+        self.assertEqual(self.seq[self.o:self.o2], self.seq[1:3])
+        self.assertEqual(self.seq[self.n:self.n2], self.seq[2:4])
 
     def test_repeat(self):
         self.o.ind = 3
         self.n.ind = 2
-        assert(self.seq * self.o == self.seq * 3)
-        assert(self.seq * self.n == self.seq * 2)
-        assert(self.o * self.seq == self.seq * 3)
-        assert(self.n * self.seq == self.seq * 2)
+        self.assertEqual(self.seq * self.o, self.seq * 3)
+        self.assertEqual(self.seq * self.n, self.seq * 2)
+        self.assertEqual(self.o * self.seq, self.seq * 3)
+        self.assertEqual(self.n * self.seq, self.seq * 2)
 
     def test_wrappers(self):
-        n = self.n
-        n.ind = 5
-        assert n.__index__() == 5
-        assert 6 .__index__() == 6
-        assert -7L.__index__() == -7
-        assert self.seq.__getitem__(n) == self.seq[5]
-        assert self.seq.__mul__(n) == self.seq * 5
-        assert self.seq.__rmul__(n) == self.seq * 5
-
-    def test_infinite_recusion(self):
-        class Trap1(int):
-            def __index__(self):
-                return self
-        class Trap2(long):
-            def __index__(self):
-                return self
-        self.failUnlessRaises(TypeError, operator.getitem, self.seq, Trap1())
-        self.failUnlessRaises(TypeError, operator.getitem, self.seq, Trap2())
+        self.o.ind = 4
+        self.n.ind = 5
+        self.assertEqual(self.seq.__getitem__(self.o), self.seq[4])
+        self.assertEqual(self.seq.__mul__(self.o), self.seq * 4)
+        self.assertEqual(self.seq.__rmul__(self.o), self.seq * 4)
+        self.assertEqual(self.seq.__getitem__(self.n), self.seq[5])
+        self.assertEqual(self.seq.__mul__(self.n), self.seq * 5)
+        self.assertEqual(self.seq.__rmul__(self.n), self.seq * 5)
+
+    def test_subclasses(self):
+        self.assertEqual(self.seq[TrapInt()], self.seq[0])
+        self.assertEqual(self.seq[TrapLong()], self.seq[0])
 
+    def test_error(self):
+        self.o.ind = 'dumb'
+        self.n.ind = 'bad'
+        indexobj = lambda x, obj: obj.seq[x]
+        self.failUnlessRaises(TypeError, indexobj, self.o, self)
+        self.failUnlessRaises(TypeError, indexobj, self.n, self)
+        sliceobj = lambda x, obj: obj.seq[x:]
+        self.failUnlessRaises(TypeError, sliceobj, self.o, self)
+        self.failUnlessRaises(TypeError, sliceobj, self.n, self)
 
-class ListTestCase(BaseTestCase):
+
+class ListTestCase(SeqTestCase):
     seq = [0,10,20,30,40,50]
 
     def test_setdelitem(self):
@@ -82,36 +131,36 @@
         del lst[self.n]
         lst[self.o] = 'X'
         lst[self.n] = 'Y'
-        assert lst == list('abYdefghXj')
+        self.assertEqual(lst, list('abYdefghXj'))
 
         lst = [5, 6, 7, 8, 9, 10, 11]
         lst.__setitem__(self.n, "here")
-        assert lst == [5, 6, "here", 8, 9, 10, 11]
+        self.assertEqual(lst, [5, 6, "here", 8, 9, 10, 11])
         lst.__delitem__(self.n)
-        assert lst == [5, 6, 8, 9, 10, 11]
+        self.assertEqual(lst, [5, 6, 8, 9, 10, 11])
 
     def test_inplace_repeat(self):
         self.o.ind = 2
         self.n.ind = 3
         lst = [6, 4]
         lst *= self.o
-        assert lst == [6, 4, 6, 4]
+        self.assertEqual(lst, [6, 4, 6, 4])
         lst *= self.n
-        assert lst == [6, 4, 6, 4] * 3
+        self.assertEqual(lst, [6, 4, 6, 4] * 3)
 
         lst = [5, 6, 7, 8, 9, 11]
         l2 = lst.__imul__(self.n)
-        assert l2 is lst
-        assert lst == [5, 6, 7, 8, 9, 11] * 3
+        self.assert_(l2 is lst)
+        self.assertEqual(lst, [5, 6, 7, 8, 9, 11] * 3)
 
 
-class TupleTestCase(BaseTestCase):
+class TupleTestCase(SeqTestCase):
     seq = (0,10,20,30,40,50)
 
-class StringTestCase(BaseTestCase):
+class StringTestCase(SeqTestCase):
     seq = "this is a test"
 
-class UnicodeTestCase(BaseTestCase):
+class UnicodeTestCase(SeqTestCase):
     seq = u"this is a test"
 
 
@@ -120,17 +169,54 @@
     def test_xrange(self):
         n = newstyle()
         n.ind = 5
-        assert xrange(1, 20)[n] == 6
-        assert xrange(1, 20).__getitem__(n) == 6
+        self.assertEqual(xrange(1, 20)[n], 6)
+        self.assertEqual(xrange(1, 20).__getitem__(n), 6)
+
+class OverflowTestCase(unittest.TestCase):
+
+    def setUp(self):
+        self.pos = 2**100
+        self.neg = -self.pos
+
+    def test_large_longs(self):
+        self.assertEqual(self.pos.__index__(), self.pos)
+        self.assertEqual(self.neg.__index__(), self.neg)
+
+    def _getitem_helper(self, base):
+        class GetItem(base):
+            def __len__(self):
+                return maxint
+            def __getitem__(self, key):
+                return key
+            def __getslice__(self, i, j):
+                return i, j
+        x = GetItem()
+        self.assertEqual(x[self.pos], self.pos)
+        self.assertEqual(x[self.neg], self.neg)
+        self.assertEqual(x[self.neg:self.pos], (-1, maxint))
+        self.assertEqual(x[self.neg:self.pos:1].indices(maxint), (0, maxint, 1))
+
+    def test_getitem(self):
+        self._getitem_helper(object)
+
+    def test_getitem_classic(self):
+        class Empty: pass
+        self._getitem_helper(Empty)
+
+    def test_sequence_repeat(self):
+        self.failUnlessRaises(OverflowError, lambda: "a" * self.pos)
+        self.failUnlessRaises(OverflowError, lambda: "a" * self.neg)
 
 
 def test_main():
     test_support.run_unittest(
+        BaseTestCase,
         ListTestCase,
         TupleTestCase,
         StringTestCase,
         UnicodeTestCase,
         XRangeTestCase,
+        OverflowTestCase,
     )
 
 if __name__ == "__main__":

Modified: stackless/trunk/Lib/test/test_inspect.py
==============================================================================
--- stackless/trunk/Lib/test/test_inspect.py	(original)
+++ stackless/trunk/Lib/test/test_inspect.py	Mon Aug 21 11:10:05 2006
@@ -274,6 +274,9 @@
     def test_with_comment_instead_of_docstring(self):
         self.assertSourceEqual(mod2.func88, 88, 90)
 
+    def test_method_in_dynamic_class(self):
+        self.assertSourceEqual(mod2.method_in_dynamic_class, 95, 97)
+
 # Helper for testing classify_class_attrs.
 def attrs_wo_objs(cls):
     return [t[:3] for t in inspect.classify_class_attrs(cls)]

Modified: stackless/trunk/Lib/test/test_logging.py
==============================================================================
--- stackless/trunk/Lib/test/test_logging.py	(original)
+++ stackless/trunk/Lib/test/test_logging.py	Mon Aug 21 11:10:05 2006
@@ -493,7 +493,7 @@
             try:
                 logging._handlers.clear()
                 logging._handlers.update(saved_handlers)
-                logging._handlerList = saved_handler_list
+                logging._handlerList[:] = saved_handler_list
                 loggerDict = logging.getLogger().manager.loggerDict
                 loggerDict.clear()
                 loggerDict.update(saved_loggers)
@@ -560,7 +560,7 @@
         try:
             logging._handlers.clear()
             logging._handlers.update(saved_handlers)
-            logging._handlerList = saved_handler_list
+            logging._handlerList[:] = saved_handler_list
             loggerDict = logging.getLogger().manager.loggerDict
             loggerDict.clear()
             loggerDict.update(saved_loggers)

Modified: stackless/trunk/Lib/test/test_mailbox.py
==============================================================================
--- stackless/trunk/Lib/test/test_mailbox.py	(original)
+++ stackless/trunk/Lib/test/test_mailbox.py	Mon Aug 21 11:10:05 2006
@@ -1,4 +1,5 @@
 import os
+import sys
 import time
 import stat
 import socket
@@ -461,7 +462,7 @@
 
     def setUp(self):
         TestMailbox.setUp(self)
-        if os.name in ('nt', 'os2'):
+        if os.name in ('nt', 'os2') or sys.platform == 'cygwin':
             self._box.colon = '!'
 
     def test_add_MM(self):
@@ -736,11 +737,13 @@
         # In the parent, sleep a bit to give the child time to acquire
         # the lock.
         time.sleep(0.5)
-        self.assertRaises(mailbox.ExternalClashError,
-                          self._box.lock)
+        try:
+            self.assertRaises(mailbox.ExternalClashError,
+                              self._box.lock)
+        finally:
+            # Wait for child to exit.  Locking should now succeed.
+            exited_pid, status = os.waitpid(pid, 0)
 
-        # Wait for child to exit.  Locking should now succeed.
-        exited_pid, status = os.waitpid(pid, 0)
         self._box.lock()
         self._box.unlock()
 

Modified: stackless/trunk/Lib/test/test_shutil.py
==============================================================================
--- stackless/trunk/Lib/test/test_shutil.py	(original)
+++ stackless/trunk/Lib/test/test_shutil.py	Mon Aug 21 11:10:05 2006
@@ -74,31 +74,51 @@
             except:
                 pass
 
-
     def test_copytree_simple(self):
+        def write_data(path, data):
+            f = open(path, "w")
+            f.write(data)
+            f.close()
+
+        def read_data(path):
+            f = open(path)
+            data = f.read()
+            f.close()
+            return data
+
         src_dir = tempfile.mkdtemp()
         dst_dir = os.path.join(tempfile.mkdtemp(), 'destination')
-        open(os.path.join(src_dir, 'test.txt'), 'w').write('123')
+
+        write_data(os.path.join(src_dir, 'test.txt'), '123')
+
         os.mkdir(os.path.join(src_dir, 'test_dir'))
-        open(os.path.join(src_dir, 'test_dir', 'test.txt'), 'w').write('456')
-        #
+        write_data(os.path.join(src_dir, 'test_dir', 'test.txt'), '456')
+
         try:
             shutil.copytree(src_dir, dst_dir)
             self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test.txt')))
             self.assertTrue(os.path.isdir(os.path.join(dst_dir, 'test_dir')))
-            self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir', 'test.txt')))
-            self.assertEqual(open(os.path.join(dst_dir, 'test.txt')).read(), '123')
-            self.assertEqual(open(os.path.join(dst_dir, 'test_dir', 'test.txt')).read(), '456')
+            self.assertTrue(os.path.isfile(os.path.join(dst_dir, 'test_dir',
+                                                        'test.txt')))
+            actual = read_data(os.path.join(dst_dir, 'test.txt'))
+            self.assertEqual(actual, '123')
+            actual = read_data(os.path.join(dst_dir, 'test_dir', 'test.txt'))
+            self.assertEqual(actual, '456')
         finally:
-            try:
-                os.remove(os.path.join(src_dir, 'test.txt'))
-                os.remove(os.path.join(dst_dir, 'test.txt'))
-                os.remove(os.path.join(src_dir, 'test_dir', 'test.txt'))
-                os.remove(os.path.join(dst_dir, 'test_dir', 'test.txt'))
-                os.removedirs(src_dir)
-                os.removedirs(dst_dir)
-            except:
-                pass
+            for path in (
+                    os.path.join(src_dir, 'test.txt'),
+                    os.path.join(dst_dir, 'test.txt'),
+                    os.path.join(src_dir, 'test_dir', 'test.txt'),
+                    os.path.join(dst_dir, 'test_dir', 'test.txt'),
+                ):
+                if os.path.exists(path):
+                    os.remove(path)
+            for path in (
+                    os.path.join(src_dir, 'test_dir'),
+                    os.path.join(dst_dir, 'test_dir'),
+                ):
+                if os.path.exists(path):
+                    os.removedirs(path)
 
 
     if hasattr(os, "symlink"):

Modified: stackless/trunk/Lib/test/test_signal.py
==============================================================================
--- stackless/trunk/Lib/test/test_signal.py	(original)
+++ stackless/trunk/Lib/test/test_signal.py	Mon Aug 21 11:10:05 2006
@@ -6,11 +6,16 @@
 if sys.platform[:3] in ('win', 'os2') or sys.platform=='riscos':
     raise TestSkipped, "Can't test signal on %s" % sys.platform
 
+MAX_DURATION = 20   # Entire test should last at most 20 sec.
+
 if verbose:
     x = '-x'
 else:
     x = '+x'
+
 pid = os.getpid()
+if verbose:
+    print "test runner's pid is", pid
 
 # Shell script that will send us asynchronous signals
 script = """
@@ -31,7 +36,7 @@
     global a_called
     a_called = True
     if verbose:
-        print "handlerA", args
+        print "handlerA invoked", args
 
 class HandlerBCalled(Exception):
     pass
@@ -40,87 +45,110 @@
     global b_called
     b_called = True
     if verbose:
-        print "handlerB", args
+        print "handlerB invoked", args
     raise HandlerBCalled, args
 
-MAX_DURATION = 20
-signal.alarm(MAX_DURATION)   # Entire test should last at most 20 sec.
+# Set up a child to send signals to us (the parent) after waiting long
+# enough to receive the alarm.  It seems we miss the alarm for some
+# reason.  This will hopefully stop the hangs on Tru64/Alpha.
+# Alas, it doesn't.  Tru64 appears to miss all the signals at times, or
+# seemingly random subsets of them, and nothing done in force_test_exit
+# so far has actually helped.
+def force_test_exit():
+    # Sigh, both imports seem necessary to avoid errors.
+    import os
+    fork_pid = os.fork()
+    if fork_pid:
+        # In parent.
+        return fork_pid
+
+    # In child.
+    import os, time
+    try:
+        # Wait 5 seconds longer than the expected alarm to give enough
+        # time for the normal sequence of events to occur.  This is
+        # just a stop-gap to try to prevent the test from hanging.
+        time.sleep(MAX_DURATION + 5)
+        print >> sys.__stdout__, '  child should not have to kill parent'
+        for signame in "SIGHUP", "SIGUSR1", "SIGUSR2", "SIGALRM":
+            os.kill(pid, getattr(signal, signame))
+            print >> sys.__stdout__, "    child sent", signame, "to", pid
+            time.sleep(1)
+    finally:
+        os._exit(0)
+
+# Install handlers.
 hup = signal.signal(signal.SIGHUP, handlerA)
 usr1 = signal.signal(signal.SIGUSR1, handlerB)
 usr2 = signal.signal(signal.SIGUSR2, signal.SIG_IGN)
 alrm = signal.signal(signal.SIGALRM, signal.default_int_handler)
 
-vereq(signal.getsignal(signal.SIGHUP), handlerA)
-vereq(signal.getsignal(signal.SIGUSR1), handlerB)
-vereq(signal.getsignal(signal.SIGUSR2), signal.SIG_IGN)
-
 try:
-    signal.signal(4242, handlerB)
-    raise TestFailed, 'expected ValueError for invalid signal # to signal()'
-except ValueError:
-    pass
 
-try:
-    signal.getsignal(4242)
-    raise TestFailed, 'expected ValueError for invalid signal # to getsignal()'
-except ValueError:
-    pass
+    signal.alarm(MAX_DURATION)
+    vereq(signal.getsignal(signal.SIGHUP), handlerA)
+    vereq(signal.getsignal(signal.SIGUSR1), handlerB)
+    vereq(signal.getsignal(signal.SIGUSR2), signal.SIG_IGN)
+    vereq(signal.getsignal(signal.SIGALRM), signal.default_int_handler)
 
-try:
-    signal.signal(signal.SIGUSR1, None)
-    raise TestFailed, 'expected TypeError for non-callable'
-except TypeError:
-    pass
+    # Try to ensure this test exits even if there is some problem with alarm.
+    # Tru64/Alpha often hangs and is ultimately killed by the buildbot.
+    fork_pid = force_test_exit()
 
-# Set up a child to send an alarm signal to us (the parent) after waiting
-# long enough to receive the alarm.  It seems we miss the alarm for some
-# reason.  This will hopefully stop the hangs on Tru64/Alpha.
-def force_test_exit():
-    # Sigh, both imports seem necessary to avoid errors.
-    import os
-    fork_pid = os.fork()
-    if fork_pid == 0:
-        # In child
-        import os, time
-        try:
-            # Wait 5 seconds longer than the expected alarm to give enough
-            # time for the normal sequence of events to occur.  This is
-            # just a stop-gap to prevent the test from hanging.
-            time.sleep(MAX_DURATION + 5)
-            print >> sys.__stdout__, '  child should not have to kill parent'
-            for i in range(3):
-                os.kill(pid, signal.SIGALARM)
-        finally:
-            os._exit(0)
-    # In parent (or error)
-    return fork_pid
+    try:
+        signal.getsignal(4242)
+        raise TestFailed('expected ValueError for invalid signal # to '
+                         'getsignal()')
+    except ValueError:
+        pass
 
-try:
-    os.system(script)
+    try:
+        signal.signal(4242, handlerB)
+        raise TestFailed('expected ValueError for invalid signal # to '
+                         'signal()')
+    except ValueError:
+        pass
 
-    # Try to ensure this test exits even if there is some problem with alarm.
-    # Tru64/Alpha sometimes hangs and is ultimately killed by the buildbot.
-    fork_pid = force_test_exit()
-    print "starting pause() loop..."
+    try:
+        signal.signal(signal.SIGUSR1, None)
+        raise TestFailed('expected TypeError for non-callable')
+    except TypeError:
+        pass
 
+    # Launch an external script to send us signals.
+    # We expect the external script to:
+    #    send HUP, which invokes handlerA to set a_called
+    #    send USR1, which invokes handlerB to set b_called and raise
+    #               HandlerBCalled
+    #    send USR2, which is ignored
+    #
+    # Then we expect the alarm to go off, and its handler raises
+    # KeyboardInterrupt, finally getting us out of the loop.
+    os.system(script)
     try:
+        print "starting pause() loop..."
         while 1:
-            if verbose:
-                print "call pause()..."
             try:
+                if verbose:
+                    print "call pause()..."
                 signal.pause()
                 if verbose:
                     print "pause() returned"
             except HandlerBCalled:
                 if verbose:
                     print "HandlerBCalled exception caught"
-                else:
-                    pass
 
     except KeyboardInterrupt:
         if verbose:
-            print "KeyboardInterrupt (assume the alarm() went off)"
+            print "KeyboardInterrupt (the alarm() went off)"
 
+    if not a_called:
+        print 'HandlerA not called'
+
+    if not b_called:
+        print 'HandlerB not called'
+
+finally:
     # Forcibly kill the child we created to ping us if there was a test error.
     try:
         # Make sure we don't kill ourself if there was a fork error.
@@ -128,16 +156,11 @@
             os.kill(fork_pid, signal.SIGKILL)
     except:
         # If the child killed us, it has probably exited.  Killing a
-        # non-existant process will raise an error which we don't care about.
+        # non-existent process will raise an error which we don't care about.
         pass
 
-    if not a_called:
-        print 'HandlerA not called'
-
-    if not b_called:
-        print 'HandlerB not called'
-
-finally:
+    # Restore handlers.
+    signal.alarm(0) # cancel alarm in case we died early
     signal.signal(signal.SIGHUP, hup)
     signal.signal(signal.SIGUSR1, usr1)
     signal.signal(signal.SIGUSR2, usr2)

Modified: stackless/trunk/Lib/test/test_socketserver.py
==============================================================================
--- stackless/trunk/Lib/test/test_socketserver.py	(original)
+++ stackless/trunk/Lib/test/test_socketserver.py	Mon Aug 21 11:10:05 2006
@@ -181,10 +181,19 @@
     if hasattr(os, 'fork') and os.name not in ('os2',):
         dgramservers.append(ForkingUnixDatagramServer)
 
+def sloppy_cleanup():
+    # See http://python.org/sf/1540386
+    # We need to reap children here otherwise a child from one server
+    # can be left running for the next server and cause a test failure.
+    time.sleep(DELAY)
+    reap_children()
+
 def testall():
     testloop(socket.AF_INET, tcpservers, MyStreamHandler, teststream)
+    sloppy_cleanup()
     testloop(socket.AF_INET, udpservers, MyDatagramHandler, testdgram)
     if hasattr(socket, 'AF_UNIX'):
+        sloppy_cleanup()
         testloop(socket.AF_UNIX, streamservers, MyStreamHandler, teststream)
         # Alas, on Linux (at least) recvfrom() doesn't return a meaningful
         # client address so this cannot work:

Modified: stackless/trunk/Lib/test/test_struct.py
==============================================================================
--- stackless/trunk/Lib/test/test_struct.py	(original)
+++ stackless/trunk/Lib/test/test_struct.py	Mon Aug 21 11:10:05 2006
@@ -15,9 +15,11 @@
 except ImportError:
     PY_STRUCT_RANGE_CHECKING = 0
     PY_STRUCT_OVERFLOW_MASKING = 1
+    PY_STRUCT_FLOAT_COERCE = 2
 else:
-    PY_STRUCT_RANGE_CHECKING = _struct._PY_STRUCT_RANGE_CHECKING
-    PY_STRUCT_OVERFLOW_MASKING = _struct._PY_STRUCT_OVERFLOW_MASKING
+    PY_STRUCT_RANGE_CHECKING = getattr(_struct, '_PY_STRUCT_RANGE_CHECKING', 0)
+    PY_STRUCT_OVERFLOW_MASKING = getattr(_struct, '_PY_STRUCT_OVERFLOW_MASKING', 0)
+    PY_STRUCT_FLOAT_COERCE = getattr(_struct, '_PY_STRUCT_FLOAT_COERCE', 0)
 
 def string_reverse(s):
     return "".join(reversed(s))
@@ -46,33 +48,40 @@
         raise TestFailed, "%s%s did not raise error" % (
             func.__name__, args)
 
+def with_warning_restore(func):
+    def _with_warning_restore(*args, **kw):
+        # The `warnings` module doesn't have an advertised way to restore
+        # its filter list.  Cheat.
+        save_warnings_filters = warnings.filters[:]
+        # Grrr, we need this function to warn every time.  Without removing
+        # the warningregistry, running test_tarfile then test_struct would fail
+        # on 64-bit platforms.
+        globals = func.func_globals
+        if '__warningregistry__' in globals:
+            del globals['__warningregistry__']
+        warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning)
+        warnings.filterwarnings("error", r""".*format requires.*""",
+                                DeprecationWarning)
+        try:
+            return func(*args, **kw)
+        finally:
+            warnings.filters[:] = save_warnings_filters[:]
+    return _with_warning_restore
+
 def deprecated_err(func, *args):
-    # The `warnings` module doesn't have an advertised way to restore
-    # its filter list.  Cheat.
-    save_warnings_filters = warnings.filters[:]
-    # Grrr, we need this function to warn every time.  Without removing
-    # the warningregistry, running test_tarfile then test_struct would fail
-    # on 64-bit platforms.
-    globals = func.func_globals
-    if '__warningregistry__' in globals:
-        del globals['__warningregistry__']
-    warnings.filterwarnings("error", r"""^struct.*""", DeprecationWarning)
-    warnings.filterwarnings("error", r""".*format requires.*""",
-                            DeprecationWarning)
     try:
-        try:
-            func(*args)
-        except (struct.error, TypeError):
-            pass
-        except DeprecationWarning:
-            if not PY_STRUCT_OVERFLOW_MASKING:
-                raise TestFailed, "%s%s expected to raise struct.error" % (
-                    func.__name__, args)
-        else:
-            raise TestFailed, "%s%s did not raise error" % (
+        func(*args)
+    except (struct.error, TypeError):
+        pass
+    except DeprecationWarning:
+        if not PY_STRUCT_OVERFLOW_MASKING:
+            raise TestFailed, "%s%s expected to raise struct.error" % (
                 func.__name__, args)
-    finally:
-        warnings.filters[:] = save_warnings_filters[:]
+    else:
+        raise TestFailed, "%s%s did not raise error" % (
+            func.__name__, args)
+deprecated_err = with_warning_restore(deprecated_err)
+
 
 simple_err(struct.calcsize, 'Z')
 
@@ -475,6 +484,9 @@
 
 test_705836()
 
+###########################################################################
+# SF bug 1229380. No struct.pack exception for some out of range integers
+
 def test_1229380():
     import sys
     for endian in ('', '>', '<'):
@@ -491,6 +503,37 @@
 if PY_STRUCT_RANGE_CHECKING:
     test_1229380()
 
+###########################################################################
+# SF bug 1530559. struct.pack raises TypeError where it used to convert.
+
+def check_float_coerce(format, number):
+    if PY_STRUCT_FLOAT_COERCE == 2:
+        # Test for pre-2.5 struct module
+        packed = struct.pack(format, number)
+        floored = struct.unpack(format, packed)[0]
+        if floored != int(number):
+            raise TestFailed("did not correcly coerce float to int")
+        return
+    try:
+        func(*args)
+    except (struct.error, TypeError):
+        if PY_STRUCT_FLOAT_COERCE:
+            raise TestFailed("expected DeprecationWarning for float coerce")
+    except DeprecationWarning:
+        if not PY_STRUCT_FLOAT_COERCE:
+            raise TestFailed("expected to raise struct.error for float coerce")
+    else:
+        raise TestFailed("did not raise error for float coerce")
+
+check_float_coerce = with_warning_restore(deprecated_err)
+
+def test_1530559():
+    for endian in ('', '>', '<'):
+        for fmt in ('B', 'H', 'I', 'L', 'b', 'h', 'i', 'l'):
+            check_float_coerce(endian + fmt, 1.0)
+            check_float_coerce(endian + fmt, 1.5)
+
+test_1530559()
 
 ###########################################################################
 # Packing and unpacking to/from buffers.

Modified: stackless/trunk/Lib/test/test_support.py
==============================================================================
--- stackless/trunk/Lib/test/test_support.py	(original)
+++ stackless/trunk/Lib/test/test_support.py	Mon Aug 21 11:10:05 2006
@@ -314,6 +314,12 @@
 _1G = 1024 * _1M
 _2G = 2 * _1G
 
+# Hack to get at the maximum value an internal index can take.
+class _Dummy:
+    def __getslice__(self, i, j):
+        return j
+MAX_Py_ssize_t = _Dummy()[:]
+
 def set_memlimit(limit):
     import re
     global max_memuse
@@ -328,7 +334,9 @@
     if m is None:
         raise ValueError('Invalid memory limit %r' % (limit,))
     memlimit = int(float(m.group(1)) * sizes[m.group(3).lower()])
-    if memlimit < 2.5*_1G:
+    if memlimit > MAX_Py_ssize_t:
+        memlimit = MAX_Py_ssize_t
+    if memlimit < _2G - 1:
         raise ValueError('Memory limit %r too low to be useful' % (limit,))
     max_memuse = memlimit
 
@@ -371,6 +379,17 @@
         return wrapper
     return decorator
 
+def bigaddrspacetest(f):
+    """Decorator for tests that fill the address space."""
+    def wrapper(self):
+        if max_memuse < MAX_Py_ssize_t:
+            if verbose:
+                sys.stderr.write("Skipping %s because of memory "
+                                 "constraint\n" % (f.__name__,))
+        else:
+            return f(self)
+    return wrapper
+
 #=======================================================================
 # Preliminary PyUNIT integration.
 

Modified: stackless/trunk/Lib/test/test_threading.py
==============================================================================
--- stackless/trunk/Lib/test/test_threading.py	(original)
+++ stackless/trunk/Lib/test/test_threading.py	Mon Aug 21 11:10:05 2006
@@ -89,7 +89,12 @@
     def test_various_ops_small_stack(self):
         if verbose:
             print 'with 256kB thread stack size...'
-        threading.stack_size(262144)
+        try:
+            threading.stack_size(262144)
+        except thread.error:
+            if verbose:
+                print 'platform does not support changing thread stack size'
+            return
         self.test_various_ops()
         threading.stack_size(0)
 
@@ -97,7 +102,12 @@
     def test_various_ops_large_stack(self):
         if verbose:
             print 'with 1MB thread stack size...'
-        threading.stack_size(0x100000)
+        try:
+            threading.stack_size(0x100000)
+        except thread.error:
+            if verbose:
+                print 'platform does not support changing thread stack size'
+            return
         self.test_various_ops()
         threading.stack_size(0)
 
@@ -121,6 +131,76 @@
                                 threading._DummyThread))
         del threading._active[tid]
 
+    # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently)
+    # exposed at the Python level.  This test relies on ctypes to get at it.
+    def test_PyThreadState_SetAsyncExc(self):
+        try:
+            import ctypes
+        except ImportError:
+            if verbose:
+                print "test_PyThreadState_SetAsyncExc can't import ctypes"
+            return  # can't do anything
+
+        set_async_exc = ctypes.pythonapi.PyThreadState_SetAsyncExc
+
+        class AsyncExc(Exception):
+            pass
+
+        exception = ctypes.py_object(AsyncExc)
+
+        # `worker_started` is set by the thread when it's inside a try/except
+        # block waiting to catch the asynchronously set AsyncExc exception.
+        # `worker_saw_exception` is set by the thread upon catching that
+        # exception.
+        worker_started = threading.Event()
+        worker_saw_exception = threading.Event()
+
+        class Worker(threading.Thread):
+            def run(self):
+                self.id = thread.get_ident()
+                self.finished = False
+
+                try:
+                    while True:
+                        worker_started.set()
+                        time.sleep(0.1)
+                except AsyncExc:
+                    self.finished = True
+                    worker_saw_exception.set()
+
+        t = Worker()
+        t.setDaemon(True) # so if this fails, we don't hang Python at shutdown
+        t.start()
+        if verbose:
+            print "    started worker thread"
+
+        # Try a thread id that doesn't make sense.
+        if verbose:
+            print "    trying nonsensical thread id"
+        result = set_async_exc(ctypes.c_long(-1), exception)
+        self.assertEqual(result, 0)  # no thread states modified
+
+        # Now raise an exception in the worker thread.
+        if verbose:
+            print "    waiting for worker thread to get started"
+        worker_started.wait()
+        if verbose:
+            print "    verifying worker hasn't exited"
+        self.assert_(not t.finished)
+        if verbose:
+            print "    attempting to raise asynch exception in worker"
+        result = set_async_exc(ctypes.c_long(t.id), exception)
+        self.assertEqual(result, 1) # one thread state modified
+        if verbose:
+            print "    waiting for worker to say it caught the exception"
+        worker_saw_exception.wait(timeout=10)
+        self.assert_(t.finished)
+        if verbose:
+            print "    all OK -- joining worker"
+        if t.finished:
+            t.join()
+        # else the thread is still running, and we have no way to kill it
+
 def test_main():
     test.test_support.run_unittest(ThreadTests)
 

Modified: stackless/trunk/Lib/test/test_threadsignals.py
==============================================================================
--- stackless/trunk/Lib/test/test_threadsignals.py	(original)
+++ stackless/trunk/Lib/test/test_threadsignals.py	Mon Aug 21 11:10:05 2006
@@ -49,7 +49,7 @@
         # and might be out of order.)  If we haven't seen
         # the signals yet, send yet another signal and
         # wait for it return.
-        if signal_blackboard[signal.SIGUSR2]['tripped'] == 0 \
+        if signal_blackboard[signal.SIGUSR1]['tripped'] == 0 \
            or signal_blackboard[signal.SIGUSR2]['tripped'] == 0:
             signal.alarm(1)
             signal.pause()

Modified: stackless/trunk/Lib/test/test_trace.py
==============================================================================
--- stackless/trunk/Lib/test/test_trace.py	(original)
+++ stackless/trunk/Lib/test/test_trace.py	Mon Aug 21 11:10:05 2006
@@ -244,8 +244,8 @@
         self.run_test(one_instr_line)
     def test_04_no_pop_blocks(self):
         self.run_test(no_pop_blocks)
-##    def test_05_no_pop_tops(self):
-##        self.run_test(no_pop_tops)
+    def test_05_no_pop_tops(self):
+        self.run_test(no_pop_tops)
     def test_06_call(self):
         self.run_test(call)
     def test_07_raise(self):

Modified: stackless/trunk/Lib/test/test_traceback.py
==============================================================================
--- stackless/trunk/Lib/test/test_traceback.py	(original)
+++ stackless/trunk/Lib/test/test_traceback.py	Mon Aug 21 11:10:05 2006
@@ -130,15 +130,24 @@
     def test_string_exception1(self):
         str_type = "String Exception"
         err = traceback.format_exception_only(str_type, None)
-        self.assert_(len(err) == 1)
-        self.assert_(err[0] == str_type + '\n')
+        self.assertEqual(len(err), 1)
+        self.assertEqual(err[0], str_type + '\n')
 
     def test_string_exception2(self):
         str_type = "String Exception"
         str_value = "String Value"
         err = traceback.format_exception_only(str_type, str_value)
-        self.assert_(len(err) == 1)
-        self.assert_(err[0] == str_type + ': ' + str_value + '\n')
+        self.assertEqual(len(err), 1)
+        self.assertEqual(err[0], str_type + ': ' + str_value + '\n')
+
+    def test_format_exception_only_bad__str__(self):
+        class X(Exception):
+            def __str__(self):
+                1/0
+        err = traceback.format_exception_only(X, X())
+        self.assertEqual(len(err), 1)
+        str_value = '<unprintable %s object>' % X.__name__
+        self.assertEqual(err[0], X.__name__ + ': ' + str_value + '\n')
 
 
 def test_main():

Modified: stackless/trunk/Lib/test/test_types.py
==============================================================================
--- stackless/trunk/Lib/test/test_types.py	(original)
+++ stackless/trunk/Lib/test/test_types.py	Mon Aug 21 11:10:05 2006
@@ -233,6 +233,7 @@
 try: buffer('asdf', -1)
 except ValueError: pass
 else: raise TestFailed, "buffer('asdf', -1) should raise ValueError"
+cmp(buffer("abc"), buffer("def")) # used to raise a warning: tp_compare didn't return -1, 0, or 1
 
 try: buffer(None)
 except TypeError: pass

Modified: stackless/trunk/Lib/test/test_uuid.py
==============================================================================
--- stackless/trunk/Lib/test/test_uuid.py	(original)
+++ stackless/trunk/Lib/test/test_uuid.py	Mon Aug 21 11:10:05 2006
@@ -16,12 +16,13 @@
     def test_UUID(self):
         equal = self.assertEqual
         ascending = []
-        for (string, curly, hex, bytes, fields, integer, urn,
+        for (string, curly, hex, bytes, bytes_le, fields, integer, urn,
              time, clock_seq, variant, version) in [
             ('00000000-0000-0000-0000-000000000000',
              '{00000000-0000-0000-0000-000000000000}',
              '00000000000000000000000000000000',
              '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
+             '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0',
              (0, 0, 0, 0, 0, 0),
              0,
              'urn:uuid:00000000-0000-0000-0000-000000000000',
@@ -30,6 +31,7 @@
              '{00010203-0405-0607-0809-0a0b0c0d0e0f}',
              '000102030405060708090a0b0c0d0e0f',
              '\0\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\x0d\x0e\x0f',
+             '\x03\x02\x01\0\x05\x04\x07\x06\x08\t\n\x0b\x0c\x0d\x0e\x0f',
              (0x00010203L, 0x0405, 0x0607, 8, 9, 0x0a0b0c0d0e0fL),
              0x000102030405060708090a0b0c0d0e0fL,
              'urn:uuid:00010203-0405-0607-0809-0a0b0c0d0e0f',
@@ -38,6 +40,7 @@
              '{02d9e6d5-9467-382e-8f9b-9300a64ac3cd}',
              '02d9e6d59467382e8f9b9300a64ac3cd',
              '\x02\xd9\xe6\xd5\x94\x67\x38\x2e\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
+             '\xd5\xe6\xd9\x02\x67\x94\x2e\x38\x8f\x9b\x93\x00\xa6\x4a\xc3\xcd',
              (0x02d9e6d5L, 0x9467, 0x382e, 0x8f, 0x9b, 0x9300a64ac3cdL),
              0x02d9e6d59467382e8f9b9300a64ac3cdL,
              'urn:uuid:02d9e6d5-9467-382e-8f9b-9300a64ac3cd',
@@ -46,6 +49,7 @@
              '{12345678-1234-5678-1234-567812345678}',
              '12345678123456781234567812345678',
              '\x12\x34\x56\x78'*4,
+             '\x78\x56\x34\x12\x34\x12\x78\x56\x12\x34\x56\x78\x12\x34\x56\x78',
              (0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678),
              0x12345678123456781234567812345678,
              'urn:uuid:12345678-1234-5678-1234-567812345678',
@@ -54,6 +58,7 @@
              '{6ba7b810-9dad-11d1-80b4-00c04fd430c8}',
              '6ba7b8109dad11d180b400c04fd430c8',
              '\x6b\xa7\xb8\x10\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
+             '\x10\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
              (0x6ba7b810L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
              0x6ba7b8109dad11d180b400c04fd430c8L,
              'urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8',
@@ -62,6 +67,7 @@
              '{6ba7b811-9dad-11d1-80b4-00c04fd430c8}',
              '6ba7b8119dad11d180b400c04fd430c8',
              '\x6b\xa7\xb8\x11\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
+             '\x11\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
              (0x6ba7b811L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
              0x6ba7b8119dad11d180b400c04fd430c8L,
              'urn:uuid:6ba7b811-9dad-11d1-80b4-00c04fd430c8',
@@ -70,6 +76,7 @@
              '{6ba7b812-9dad-11d1-80b4-00c04fd430c8}',
              '6ba7b8129dad11d180b400c04fd430c8',
              '\x6b\xa7\xb8\x12\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
+             '\x12\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
              (0x6ba7b812L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
              0x6ba7b8129dad11d180b400c04fd430c8L,
              'urn:uuid:6ba7b812-9dad-11d1-80b4-00c04fd430c8',
@@ -78,6 +85,7 @@
              '{6ba7b814-9dad-11d1-80b4-00c04fd430c8}',
              '6ba7b8149dad11d180b400c04fd430c8',
              '\x6b\xa7\xb8\x14\x9d\xad\x11\xd1\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
+             '\x14\xb8\xa7\x6b\xad\x9d\xd1\x11\x80\xb4\x00\xc0\x4f\xd4\x30\xc8',
              (0x6ba7b814L, 0x9dad, 0x11d1, 0x80, 0xb4, 0x00c04fd430c8L),
              0x6ba7b8149dad11d180b400c04fd430c8L,
              'urn:uuid:6ba7b814-9dad-11d1-80b4-00c04fd430c8',
@@ -86,6 +94,7 @@
              '{7d444840-9dc0-11d1-b245-5ffdce74fad2}',
              '7d4448409dc011d1b2455ffdce74fad2',
              '\x7d\x44\x48\x40\x9d\xc0\x11\xd1\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
+             '\x40\x48\x44\x7d\xc0\x9d\xd1\x11\xb2\x45\x5f\xfd\xce\x74\xfa\xd2',
              (0x7d444840L, 0x9dc0, 0x11d1, 0xb2, 0x45, 0x5ffdce74fad2L),
              0x7d4448409dc011d1b2455ffdce74fad2L,
              'urn:uuid:7d444840-9dc0-11d1-b245-5ffdce74fad2',
@@ -94,6 +103,7 @@
              '{e902893a-9d22-3c7e-a7b8-d6e313b71d9f}',
              'e902893a9d223c7ea7b8d6e313b71d9f',
              '\xe9\x02\x89\x3a\x9d\x22\x3c\x7e\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
+             '\x3a\x89\x02\xe9\x22\x9d\x7e\x3c\xa7\xb8\xd6\xe3\x13\xb7\x1d\x9f',
              (0xe902893aL, 0x9d22, 0x3c7e, 0xa7, 0xb8, 0xd6e313b71d9fL),
              0xe902893a9d223c7ea7b8d6e313b71d9fL,
              'urn:uuid:e902893a-9d22-3c7e-a7b8-d6e313b71d9f',
@@ -102,6 +112,7 @@
              '{eb424026-6f54-4ef8-a4d0-bb658a1fc6cf}',
              'eb4240266f544ef8a4d0bb658a1fc6cf',
              '\xeb\x42\x40\x26\x6f\x54\x4e\xf8\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
+             '\x26\x40\x42\xeb\x54\x6f\xf8\x4e\xa4\xd0\xbb\x65\x8a\x1f\xc6\xcf',
              (0xeb424026L, 0x6f54, 0x4ef8, 0xa4, 0xd0, 0xbb658a1fc6cfL),
              0xeb4240266f544ef8a4d0bb658a1fc6cfL,
              'urn:uuid:eb424026-6f54-4ef8-a4d0-bb658a1fc6cf',
@@ -110,6 +121,7 @@
              '{f81d4fae-7dec-11d0-a765-00a0c91e6bf6}',
              'f81d4fae7dec11d0a76500a0c91e6bf6',
              '\xf8\x1d\x4f\xae\x7d\xec\x11\xd0\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
+             '\xae\x4f\x1d\xf8\xec\x7d\xd0\x11\xa7\x65\x00\xa0\xc9\x1e\x6b\xf6',
              (0xf81d4faeL, 0x7dec, 0x11d0, 0xa7, 0x65, 0x00a0c91e6bf6L),
              0xf81d4fae7dec11d0a76500a0c91e6bf6L,
              'urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6',
@@ -118,6 +130,7 @@
              '{fffefdfc-fffe-fffe-fffe-fffefdfcfbfa}',
              'fffefdfcfffefffefffefffefdfcfbfa',
              '\xff\xfe\xfd\xfc\xff\xfe\xff\xfe\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
+             '\xfc\xfd\xfe\xff\xfe\xff\xfe\xff\xff\xfe\xff\xfe\xfd\xfc\xfb\xfa',
              (0xfffefdfcL, 0xfffe, 0xfffe, 0xff, 0xfe, 0xfffefdfcfbfaL),
              0xfffefdfcfffefffefffefffefdfcfbfaL,
              'urn:uuid:fffefdfc-fffe-fffe-fffe-fffefdfcfbfa',
@@ -126,6 +139,7 @@
              '{ffffffff-ffff-ffff-ffff-ffffffffffff}',
              'ffffffffffffffffffffffffffffffff',
              '\xff'*16,
+             '\xff'*16,
              (0xffffffffL, 0xffffL, 0xffffL, 0xff, 0xff, 0xffffffffffffL),
              0xffffffffffffffffffffffffffffffffL,
              'urn:uuid:ffffffff-ffff-ffff-ffff-ffffffffffff',
@@ -134,12 +148,14 @@
             equivalents = []
             # Construct each UUID in several different ways.
             for u in [uuid.UUID(string), uuid.UUID(curly), uuid.UUID(hex),
-                      uuid.UUID(bytes=bytes), uuid.UUID(fields=fields),
-                      uuid.UUID(int=integer), uuid.UUID(urn)]:
+                      uuid.UUID(bytes=bytes), uuid.UUID(bytes_le=bytes_le),
+                      uuid.UUID(fields=fields), uuid.UUID(int=integer),
+                      uuid.UUID(urn)]:
                 # Test all conversions and properties of the UUID object.
                 equal(str(u), string)
                 equal(int(u), integer)
                 equal(u.bytes, bytes)
+                equal(u.bytes_le, bytes_le)
                 equal(u.fields, fields)
                 equal(u.time_low, fields[0])
                 equal(u.time_mid, fields[1])
@@ -189,6 +205,11 @@
         badvalue(lambda: uuid.UUID(bytes='\0'*15))
         badvalue(lambda: uuid.UUID(bytes='\0'*17))
 
+        # Badly formed bytes_le.
+        badvalue(lambda: uuid.UUID(bytes_le='abc'))
+        badvalue(lambda: uuid.UUID(bytes_le='\0'*15))
+        badvalue(lambda: uuid.UUID(bytes_le='\0'*17))
+
         # Badly formed fields.
         badvalue(lambda: uuid.UUID(fields=(1,)))
         badvalue(lambda: uuid.UUID(fields=(1, 2, 3, 4, 5)))
@@ -221,51 +242,43 @@
         uuid.UUID(h)
         uuid.UUID(hex=h)
         uuid.UUID(bytes=b)
+        uuid.UUID(bytes_le=b)
         uuid.UUID(fields=f)
         uuid.UUID(int=i)
 
         # Wrong number of arguments (positional).
         badtype(lambda: uuid.UUID())
         badtype(lambda: uuid.UUID(h, b))
-        badtype(lambda: uuid.UUID(h, b, f))
-        badtype(lambda: uuid.UUID(h, b, f, i))
-
-        # Duplicate arguments (named).
-        badtype(lambda: uuid.UUID(hex=h, bytes=b))
-        badtype(lambda: uuid.UUID(hex=h, fields=f))
-        badtype(lambda: uuid.UUID(hex=h, int=i))
-        badtype(lambda: uuid.UUID(bytes=b, fields=f))
-        badtype(lambda: uuid.UUID(bytes=b, int=i))
-        badtype(lambda: uuid.UUID(fields=f, int=i))
-        badtype(lambda: uuid.UUID(hex=h, bytes=b, fields=f))
-        badtype(lambda: uuid.UUID(hex=h, bytes=b, int=i))
-        badtype(lambda: uuid.UUID(hex=h, fields=f, int=i))
-        badtype(lambda: uuid.UUID(bytes=b, int=i, fields=f))
-        badtype(lambda: uuid.UUID(hex=h, bytes=b, int=i, fields=f))
-
-        # Duplicate arguments (positional and named).
-        badtype(lambda: uuid.UUID(h, hex=h))
-        badtype(lambda: uuid.UUID(h, bytes=b))
-        badtype(lambda: uuid.UUID(h, fields=f))
-        badtype(lambda: uuid.UUID(h, int=i))
-        badtype(lambda: uuid.UUID(h, hex=h, bytes=b))
-        badtype(lambda: uuid.UUID(h, hex=h, fields=f))
-        badtype(lambda: uuid.UUID(h, hex=h, int=i))
-        badtype(lambda: uuid.UUID(h, bytes=b, fields=f))
-        badtype(lambda: uuid.UUID(h, bytes=b, int=i))
-        badtype(lambda: uuid.UUID(h, fields=f, int=i))
-        badtype(lambda: uuid.UUID(h, hex=h, bytes=b, fields=f))
-        badtype(lambda: uuid.UUID(h, hex=h, bytes=b, int=i))
-        badtype(lambda: uuid.UUID(h, hex=h, fields=f, int=i))
-        badtype(lambda: uuid.UUID(h, bytes=b, int=i, fields=f))
-        badtype(lambda: uuid.UUID(h, hex=h, bytes=b, int=i, fields=f))
+        badtype(lambda: uuid.UUID(h, b, b))
+        badtype(lambda: uuid.UUID(h, b, b, f))
+        badtype(lambda: uuid.UUID(h, b, b, f, i))
+
+        # Duplicate arguments.
+        for hh in [[], [('hex', h)]]:
+            for bb in [[], [('bytes', b)]]:
+                for bble in [[], [('bytes_le', b)]]:
+                    for ii in [[], [('int', i)]]:
+                        for ff in [[], [('fields', f)]]:
+                            args = dict(hh + bb + bble + ii + ff)
+                            if len(args) != 0:
+                                badtype(lambda: uuid.UUID(h, **args))
+                            if len(args) != 1:
+                                badtype(lambda: uuid.UUID(**args))
 
         # Immutability.
         u = uuid.UUID(h)
         badtype(lambda: setattr(u, 'hex', h))
         badtype(lambda: setattr(u, 'bytes', b))
+        badtype(lambda: setattr(u, 'bytes_le', b))
         badtype(lambda: setattr(u, 'fields', f))
         badtype(lambda: setattr(u, 'int', i))
+        badtype(lambda: setattr(u, 'time_low', 0))
+        badtype(lambda: setattr(u, 'time_mid', 0))
+        badtype(lambda: setattr(u, 'time_hi_version', 0))
+        badtype(lambda: setattr(u, 'time_hi_version', 0))
+        badtype(lambda: setattr(u, 'clock_seq_hi_variant', 0))
+        badtype(lambda: setattr(u, 'clock_seq_low', 0))
+        badtype(lambda: setattr(u, 'node', 0))
 
     def check_node(self, node, source):
         individual_group_bit = (node >> 40L) & 1
@@ -356,11 +369,17 @@
     def test_uuid1(self):
         equal = self.assertEqual
 
-        # Make sure uuid4() generates UUIDs that are actually version 1.
+        # Make sure uuid1() generates UUIDs that are actually version 1.
         for u in [uuid.uuid1() for i in range(10)]:
             equal(u.variant, uuid.RFC_4122)
             equal(u.version, 1)
 
+        # Make sure the generated UUIDs are actually unique.
+        uuids = {}
+        for u in [uuid.uuid1() for i in range(1000)]:
+            uuids[u] = 1
+        equal(len(uuids.keys()), 1000)
+
         # Make sure the supplied node ID appears in the UUID.
         u = uuid.uuid1(0)
         equal(u.node, 0)
@@ -408,6 +427,12 @@
             equal(u.variant, uuid.RFC_4122)
             equal(u.version, 4)
 
+        # Make sure the generated UUIDs are actually unique.
+        uuids = {}
+        for u in [uuid.uuid1() for i in range(1000)]:
+            uuids[u] = 1
+        equal(len(uuids.keys()), 1000)
+
     def test_uuid5(self):
         equal = self.assertEqual
 

Modified: stackless/trunk/Lib/test/test_xml_etree_c.py
==============================================================================
--- stackless/trunk/Lib/test/test_xml_etree_c.py	(original)
+++ stackless/trunk/Lib/test/test_xml_etree_c.py	Mon Aug 21 11:10:05 2006
@@ -204,6 +204,17 @@
         "<?xml version='1.0' encoding='%s'?><xml />" % encoding
         )
 
+def bug_1534630():
+    """
+    >>> bob = ET.TreeBuilder()
+    >>> e = bob.data("data")
+    >>> e = bob.start("tag", {})
+    >>> e = bob.end("tag")
+    >>> e = bob.close()
+    >>> serialize(ET, e)
+    '<tag />'
+    """
+
 def test_main():
     from test import test_xml_etree_c
     test_support.run_doctest(test_xml_etree_c, verbosity=True)

Modified: stackless/trunk/Lib/tokenize.py
==============================================================================
--- stackless/trunk/Lib/tokenize.py	(original)
+++ stackless/trunk/Lib/tokenize.py	Mon Aug 21 11:10:05 2006
@@ -273,7 +273,8 @@
             while column < indents[-1]:
                 if column not in indents:
                     raise IndentationError(
-                        "unindent does not match any outer indentation level")
+                        "unindent does not match any outer indentation level",
+                        ("<tokenize>", lnum, pos, line))
                 indents = indents[:-1]
                 yield (DEDENT, '', (lnum, pos), (lnum, pos), line)
 

Modified: stackless/trunk/Lib/trace.py
==============================================================================
--- stackless/trunk/Lib/trace.py	(original)
+++ stackless/trunk/Lib/trace.py	Mon Aug 21 11:10:05 2006
@@ -179,9 +179,11 @@
     # looking in sys.path for the longest matching prefix.  We'll
     # assume that the rest is the package name.
 
+    comparepath = os.path.normcase(path)
     longest = ""
     for dir in sys.path:
-        if path.startswith(dir) and path[len(dir)] == os.path.sep:
+        dir = os.path.normcase(dir)
+        if comparepath.startswith(dir) and comparepath[len(dir)] == os.sep:
             if len(dir) > len(longest):
                 longest = dir
 

Modified: stackless/trunk/Lib/traceback.py
==============================================================================
--- stackless/trunk/Lib/traceback.py	(original)
+++ stackless/trunk/Lib/traceback.py	Mon Aug 21 11:10:05 2006
@@ -202,10 +202,11 @@
 
 def _format_final_exc_line(etype, value):
     """Return a list of a single line -- normal case for format_exception_only"""
-    if value is None or not str(value):
+    valuestr = _some_str(value)
+    if value is None or not valuestr:
         line = "%s\n" % etype
     else:
-        line = "%s: %s\n" % (etype, _some_str(value))
+        line = "%s: %s\n" % (etype, valuestr)
     return line
 
 def _some_str(value):

Modified: stackless/trunk/Lib/uuid.py
==============================================================================
--- stackless/trunk/Lib/uuid.py	(original)
+++ stackless/trunk/Lib/uuid.py	Mon Aug 21 11:10:05 2006
@@ -45,8 +45,6 @@
 """
 
 __author__ = 'Ka-Ping Yee <ping at zesty.ca>'
-__date__ = '$Date: 2006/06/12 23:15:40 $'.split()[1].replace('/', '-')
-__version__ = '$Revision: 1.30 $'.split()[1]
 
 RESERVED_NCS, RFC_4122, RESERVED_MICROSOFT, RESERVED_FUTURE = [
     'reserved for NCS compatibility', 'specified in RFC 4122',
@@ -57,15 +55,21 @@
     UUID objects are immutable, hashable, and usable as dictionary keys.
     Converting a UUID to a string with str() yields something in the form
     '12345678-1234-1234-1234-123456789abc'.  The UUID constructor accepts
-    four possible forms: a similar string of hexadecimal digits, or a
-    string of 16 raw bytes as an argument named 'bytes', or a tuple of
-    six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
-    48-bit values respectively) as an argument named 'fields', or a single
-    128-bit integer as an argument named 'int'.
+    five possible forms: a similar string of hexadecimal digits, or a tuple
+    of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and
+    48-bit values respectively) as an argument named 'fields', or a string
+    of 16 bytes (with all the integer fields in big-endian order) as an
+    argument named 'bytes', or a string of 16 bytes (with the first three
+    fields in little-endian order) as an argument named 'bytes_le', or a
+    single 128-bit integer as an argument named 'int'.
 
     UUIDs have these read-only attributes:
 
-        bytes       the UUID as a 16-byte string
+        bytes       the UUID as a 16-byte string (containing the six
+                    integer fields in big-endian byte order)
+
+        bytes_le    the UUID as a 16-byte string (with time_low, time_mid,
+                    and time_hi_version in little-endian byte order)
 
         fields      a tuple of the six integer fields of the UUID,
                     which are also available as six individual attributes
@@ -94,10 +98,11 @@
                     when the variant is RFC_4122)
     """
 
-    def __init__(self, hex=None, bytes=None, fields=None, int=None,
-                       version=None):
+    def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None,
+                       int=None, version=None):
         r"""Create a UUID from either a string of 32 hexadecimal digits,
-        a string of 16 bytes as the 'bytes' argument, a tuple of six
+        a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
+        in little-endian order as the 'bytes_le' argument, a tuple of six
         integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
         8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
         the 'fields' argument, or a single 128-bit integer as the 'int'
@@ -109,23 +114,31 @@
         UUID('12345678123456781234567812345678')
         UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
         UUID(bytes='\x12\x34\x56\x78'*4)
+        UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
+                      '\x12\x34\x56\x78\x12\x34\x56\x78')
         UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
         UUID(int=0x12345678123456781234567812345678)
 
-        Exactly one of 'hex', 'bytes', 'fields', or 'int' must be given.
-        The 'version' argument is optional; if given, the resulting UUID
-        will have its variant and version number set according to RFC 4122,
-        overriding bits in the given 'hex', 'bytes', 'fields', or 'int'.
+        Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', or 'int' must
+        be given.  The 'version' argument is optional; if given, the resulting
+        UUID will have its variant and version set according to RFC 4122,
+        overriding the given 'hex', 'bytes', 'bytes_le', 'fields', or 'int'.
         """
 
-        if [hex, bytes, fields, int].count(None) != 3:
-            raise TypeError('need just one of hex, bytes, fields, or int')
+        if [hex, bytes, bytes_le, fields, int].count(None) != 4:
+            raise TypeError('need one of hex, bytes, bytes_le, fields, or int')
         if hex is not None:
             hex = hex.replace('urn:', '').replace('uuid:', '')
             hex = hex.strip('{}').replace('-', '')
             if len(hex) != 32:
                 raise ValueError('badly formed hexadecimal UUID string')
             int = long(hex, 16)
+        if bytes_le is not None:
+            if len(bytes_le) != 16:
+                raise ValueError('bytes_le is not a 16-char string')
+            bytes = (bytes_le[3] + bytes_le[2] + bytes_le[1] + bytes_le[0] +
+                     bytes_le[5] + bytes_le[4] + bytes_le[7] + bytes_le[6] +
+                     bytes_le[8:])
         if bytes is not None:
             if len(bytes) != 16:
                 raise ValueError('bytes is not a 16-char string')
@@ -194,6 +207,13 @@
 
     bytes = property(get_bytes)
 
+    def get_bytes_le(self):
+        bytes = self.bytes
+        return (bytes[3] + bytes[2] + bytes[1] + bytes[0] +
+                bytes[5] + bytes[4] + bytes[7] + bytes[6] + bytes[8:])
+
+    bytes_le = property(get_bytes_le)
+
     def get_fields(self):
         return (self.time_low, self.time_mid, self.time_hi_version,
                 self.clock_seq_hi_variant, self.clock_seq_low, self.node)
@@ -448,6 +468,8 @@
         if _node is not None:
             return _node
 
+_last_timestamp = None
+
 def uuid1(node=None, clock_seq=None):
     """Generate a UUID from a host ID, sequence number, and the current time.
     If 'node' is not given, getnode() is used to obtain the hardware
@@ -460,11 +482,15 @@
         _uuid_generate_time(_buffer)
         return UUID(bytes=_buffer.raw)
 
+    global _last_timestamp
     import time
     nanoseconds = int(time.time() * 1e9)
     # 0x01b21dd213814000 is the number of 100-ns intervals between the
     # UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
     timestamp = int(nanoseconds/100) + 0x01b21dd213814000L
+    if timestamp == _last_timestamp:
+        timestamp += 1
+    _last_timestamp = timestamp
     if clock_seq is None:
         import random
         clock_seq = random.randrange(1<<14L) # instead of stable storage

Modified: stackless/trunk/Lib/webbrowser.py
==============================================================================
--- stackless/trunk/Lib/webbrowser.py	(original)
+++ stackless/trunk/Lib/webbrowser.py	Mon Aug 21 11:10:05 2006
@@ -434,13 +434,13 @@
     # The default Gnome browser
     if _iscommand("gconftool-2"):
         # get the web browser string from gconftool
-        gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command'
+        gc = 'gconftool-2 -g /desktop/gnome/url-handlers/http/command 2>/dev/null'
         out = os.popen(gc)
         commd = out.read().strip()
         retncode = out.close()
 
         # if successful, register it
-        if retncode == None and len(commd) != 0:
+        if retncode is None and commd:
             register("gnome", None, BackgroundBrowser(commd))
 
     # First, the Mozilla/Netscape browsers

Modified: stackless/trunk/Misc/ACKS
==============================================================================
--- stackless/trunk/Misc/ACKS	(original)
+++ stackless/trunk/Misc/ACKS	Mon Aug 21 11:10:05 2006
@@ -412,6 +412,7 @@
 Michael McLay
 Gordon McMillan
 Jay T. Miller
+Chris McDonough
 Andrew McNamara
 Caolan McNamara
 Craig McPheeters

Modified: stackless/trunk/Misc/NEWS
==============================================================================
--- stackless/trunk/Misc/NEWS	(original)
+++ stackless/trunk/Misc/NEWS	Mon Aug 21 11:10:05 2006
@@ -4,6 +4,173 @@
 
 (editors: check NEWS.help for information about editing NEWS using ReST.)
 
+What's New in Python 2.5 release candidate 1?
+=============================================
+
+*Release date: 17-AUG-2006*
+
+Core and builtins
+-----------------
+
+- Unicode objects will no longer raise an exception when being
+  compared equal or unequal to a string and a UnicodeDecodeError
+  exception occurs, e.g. as result of a decoding failure.
+
+  Instead, the equal (==) and unequal (!=) comparison operators will
+  now issue a UnicodeWarning and interpret the two objects as
+  unequal. The UnicodeWarning can be filtered as desired using
+  the warning framework, e.g. silenced completely, turned into an
+  exception, logged, etc.
+
+  Note that compare operators other than equal and unequal will still
+  raise UnicodeDecodeError exceptions as they've always done.
+
+- Fix segfault when doing string formatting on subclasses of long.
+
+- Fix bug related to __len__ functions using values > 2**32 on 64-bit machines
+  with new-style classes.
+
+- Fix bug related to __len__ functions returning negative values with
+  classic classes.
+
+- Patch #1538606, Fix __index__() clipping.  There were some problems
+  discovered with the API and how integers that didn't fit into Py_ssize_t
+  were handled.  This patch attempts to provide enough alternatives
+  to effectively use __index__.
+
+- Bug #1536021: __hash__ may now return long int; the final hash
+  value is obtained by invoking hash on the long int.
+
+- Bug #1536786: buffer comparison could emit a RuntimeWarning.
+
+- Bug #1535165: fixed a segfault in input() and raw_input() when
+  sys.stdin is closed.
+
+- On Windows, the PyErr_Warn function is now exported from
+  the Python dll again.
+
+- Bug #1191458: tracing over for loops now produces a line event
+  on each iteration.  Fixing this problem required changing the .pyc
+  magic number.  This means that .pyc files generated before 2.5c1
+  will be regenerated.
+
+- Bug #1333982: string/number constants were inappropriately stored
+  in the byte code and co_consts even if they were not used, ie
+  immediately popped off the stack.
+
+- Fixed a reference-counting problem in property().
+
+
+Library
+-------
+
+- Fix a bug in the ``compiler`` package that caused invalid code to be
+  generated for generator expressions.
+
+- The distutils version has been changed to 2.5.0. The change to
+  keep it programmatically in sync with the Python version running
+  the code (introduced in 2.5b3) has been reverted. It will continue
+  to be maintained manually as static string literal.
+
+- If the Python part of a ctypes callback function returns None,
+  and this cannot be converted to the required C type, an exception is
+  printed with PyErr_WriteUnraisable.  Before this change, the C
+  callback returned arbitrary values to the calling code.
+
+- The __repr__ method of a NULL ctypes.py_object() no longer raises
+  an exception.
+
+- uuid.UUID now has a bytes_le attribute. This returns the UUID in 
+  little-endian byte order for Windows. In addition, uuid.py gained some
+  workarounds for clocks with low resolution, to stop the code yielding
+  duplicate UUIDs.
+
+- Patch #1540892: site.py Quitter() class attempts to close sys.stdin
+  before raising SystemExit, allowing IDLE to honor quit() and exit().
+
+- Bug #1224621: make tabnanny recognize IndentationErrors raised by tokenize.
+
+- Patch #1536071: trace.py should now find the full module name of a
+  file correctly even on Windows.
+
+- logging's atexit hook now runs even if the rest of the module has
+  already been cleaned up.
+
+- Bug #1112549, fix DoS attack on cgi.FieldStorage.
+
+- Bug #1531405, format_exception no longer raises an exception if
+  str(exception) raised an exception.
+
+- Fix a bug in the ``compiler`` package that caused invalid code to be
+  generated for nested functions.
+
+
+Extension Modules
+-----------------
+
+- Patch #1511317: don't crash on invalid hostname (alias) info.
+
+- Patch #1535500: fix segfault in BZ2File.writelines and make sure it
+  raises the correct exceptions.
+
+- Patch # 1536908: enable building ctypes on OpenBSD/AMD64.  The
+  '-no-stack-protector' compiler flag for OpenBSD has been removed.
+
+- Patch #1532975 was applied, which fixes Bug #1533481: ctypes now
+  uses the _as_parameter_ attribute when objects are passed to foreign
+  function calls.  The ctypes version number was changed to 1.0.1.
+
+- Bug #1530559, struct.pack raises TypeError where it used to convert.
+  Passing float arguments to struct.pack when integers are expected
+  now triggers a DeprecationWarning.
+
+
+Tests
+-----
+
+- test_socketserver should now work on cygwin and not fail sporadically
+  on other platforms.
+
+- test_mailbox should now work on cygwin versions 2006-08-10 and later.
+
+- Bug #1535182: really test the xreadlines() method of bz2 objects.
+
+- test_threading now skips testing alternate thread stack sizes on
+  platforms that don't support changing thread stack size.
+
+
+Documentation
+-------------
+
+- Patch #1534922: unittest docs were corrected and enhanced.
+
+
+Build
+-----
+
+- Bug #1535502, build _hashlib on Windows, and use masm assembler
+  code in OpenSSL.
+
+- Bug #1534738, win32 debug version of _msi should be _msi_d.pyd.
+
+- Bug #1530448, ctypes build failure on Solaris 10 was fixed.
+
+
+C API
+-----
+
+- New API for Unicode rich comparisons: PyUnicode_RichCompare()
+
+- Bug #1069160.  Internal correctness changes were made to
+  ``PyThreadState_SetAsyncExc()``.  A test case was added, and
+  the documentation was changed to state that the return value
+  is always 1 (normal) or 0 (if the specified thread wasn't found).
+
+
+Mac
+---
+
+
 What's New in Python 2.5 beta 3?
 ================================
 
@@ -12,7 +179,7 @@
 Core and builtins
 -----------------
 
-- _PyWeakref_GetWeakrefCount() now returns a Py_ssize_t, it previously
+- _PyWeakref_GetWeakrefCount() now returns a Py_ssize_t; it previously
   returned a long (see PEP 353).
 
 - Bug #1515471: string.replace() accepts character buffers again.
@@ -51,10 +218,10 @@
 
 - Bug #1520864: unpacking singleton tuples in a 'for' loop (for x, in) works
   again.  Fixing this problem required changing the .pyc magic number.
-  This means that .pyc files generated before 2.5c1 will be regenerated.
+  This means that .pyc files generated before 2.5b3 will be regenerated.
 
 - Bug #1524317:  Compiling Python ``--without-threads`` failed.
-  The Python core compiles again then, and, in a build without threads, the
+  The Python core compiles again, and, in a build without threads, the
   new ``sys._current_frames()`` returns a dictionary with one entry,
   mapping the faux "thread id" 0 to the current frame.
 
@@ -70,14 +237,14 @@
 - os.urandom no longer masks unrelated exceptions like SystemExit or
   KeyboardInterrupt.
 
-- Bug #1525866: Don't copy directory stat times in 
+- Bug #1525866: Don't copy directory stat times in
   shutil.copytree on Windows
 
 - Bug #1002398: The documentation for os.path.sameopenfile now correctly
   refers to file descriptors, not file objects.
 
-- Rename of the xml package to xmlcore, and the import hackery done to
-  make it appear at both names, has been removed.  Bug #1511497,
+- The renaming of the xml package to xmlcore, and the import hackery done 
+  to make it appear at both names, has been removed.  Bug #1511497,
   #1513611, and probably others.
 
 - Bug #1441397: The compiler module now recognizes module and function
@@ -89,7 +256,7 @@
   side effects from one test to the next affect outcomes.  ``DocTestFinder``
   has been changed to sort the list of tests it returns.
 
-- The distutils version has been changed to 2.5.0, and are now kept
+- The distutils version has been changed to 2.5.0, and is now kept
   in sync with sys.version_info[:3].
 
 - Bug #978833: Really close underlying socket in _socketobject.close.
@@ -203,7 +370,7 @@
 
 - Bug #1527397: PythonLauncher now launches scripts with the working directory
   set to the directory that contains the script instead of the user home
-  directory. That latter was an implementation accident and not what users 
+  directory. That latter was an implementation accident and not what users
   expect.
 
 
@@ -376,6 +543,7 @@
 
 - Patch #1504046: Add documentation for xml.etree.
 
+
 What's New in Python 2.5 beta 1?
 ================================
 

Modified: stackless/trunk/Misc/PURIFY.README
==============================================================================
--- stackless/trunk/Misc/PURIFY.README	(original)
+++ stackless/trunk/Misc/PURIFY.README	Mon Aug 21 11:10:05 2006
@@ -1,6 +1,6 @@
 Purify (tm) and Quantify (tm) are commercial software quality
-assurance tools available from Rational Software Corporation
-<http://www.rational.com/>.  Purify is essentially a memory access
+assurance tools available from IBM <http://www.ibm.com/software/rational/>.
+Purify is essentially a memory access
 verifier and leak detector; Quantify is a C level profiler.  The rest
 of this file assumes you generally know how to use Purify and
 Quantify, and that you have installed valid licenses for these
@@ -20,6 +20,17 @@
 
     make PURIFY=quantify
 
+Starting with Python 2.3, pymalloc is enabled by default.  This
+will cause many supurious warnings.  Modify Objects/obmalloc.c
+and enable Py_USING_MEMORY_DEBUGGER by uncommenting it.
+README.valgrind has more details about why this is necessary.
+See below about setting up suppressions.  Some tests may not
+run well with Purify due to heavy memory or CPU usage.  These
+tests may include: test_largefile, test_import, and test_long.
+
+Please report any findings (problems or no warnings) to python-dev at python.org.
+It may be useful to submit a bug report for any problems.  
+
 When running the regression test (make test), I have found it useful
 to set my PURIFYOPTIONS environment variable using the following
 (bash) shell function.  Check out the Purify documentation for
@@ -52,6 +63,11 @@
     suppress umr ...; "nismodule.c"
     suppress umr ...; "pwdmodule.c"
 
+Note: this list is very old and may not be accurate any longer.
+It's possible some of these no longer need to be suppressed.
+You will also need to suppress warnings (at least umr)
+from Py_ADDRESS_IN_RANGE.
+
 This will still leave you with just a few UMR, mostly in the readline
 library, which you can safely ignore.  A lot of work has gone into
 Python 1.5 to plug as many leaks as possible.

Modified: stackless/trunk/Misc/README.klocwork
==============================================================================
--- stackless/trunk/Misc/README.klocwork	(original)
+++ stackless/trunk/Misc/README.klocwork	Mon Aug 21 11:10:05 2006
@@ -23,4 +23,8 @@
 False positives were also annotated so that the comments can
 be reviewed and reversed if the analysis was incorrect.
 
+A second run was performed on 10-Aug-2006.  The tool was tuned to remove
+some false positives and perform some additional checks.  ~150 new
+warnings were produced, primarily related to dereferencing NULL pointers.
+
 Contact python-dev at python.org for more information.

Modified: stackless/trunk/Misc/RPM/python-2.5.spec
==============================================================================
--- stackless/trunk/Misc/RPM/python-2.5.spec	(original)
+++ stackless/trunk/Misc/RPM/python-2.5.spec	Mon Aug 21 11:10:05 2006
@@ -33,7 +33,7 @@
 #################################
 
 %define name python
-%define version 2.5b3
+%define version 2.5c1
 %define libvers 2.5
 %define release 1pydotorg
 %define __prefix /usr

Modified: stackless/trunk/Modules/Setup.dist
==============================================================================
--- stackless/trunk/Modules/Setup.dist	(original)
+++ stackless/trunk/Modules/Setup.dist	Mon Aug 21 11:10:05 2006
@@ -59,7 +59,7 @@
 #
 # In addition, *static* explicitly declares the following modules to
 # be static.  Lines containing "*static*" and "*shared*" may thus
-# alternate thoughout this file.
+# alternate throughout this file.
 
 # NOTE: As a standard policy, as many modules as can be supported by a
 # platform should be present.  The distribution comes with all modules
@@ -234,16 +234,19 @@
 #rgbimg rgbimgmodule.c	# Read SGI RGB image files (but coded portably)
 
 
-# The md5 module implements the RSA Data Security, Inc. MD5
+# Note that the _md5 and _sha modules are normally only built if the
+# system does not have the OpenSSL libs containing an optimized version.
+
+# The _md5 module implements the RSA Data Security, Inc. MD5
 # Message-Digest Algorithm, described in RFC 1321.  The necessary files
 # md5.c and md5.h are included here.
 
-#md5 md5module.c md5.c
+#_md5 md5module.c md5.c
 
 
-# The sha module implements the SHA checksum algorithm.
+# The _sha module implements the SHA checksum algorithm.
 # (NIST's Secure Hash Algorithm.)
-#sha shamodule.c
+#_sha shamodule.c
 
 
 # SGI IRIX specific modules -- off by default.

Modified: stackless/trunk/Modules/_bsddb.c
==============================================================================
--- stackless/trunk/Modules/_bsddb.c	(original)
+++ stackless/trunk/Modules/_bsddb.c	Mon Aug 21 11:10:05 2006
@@ -1797,7 +1797,6 @@
     DBC** cursors;
     DBC*  dbc;
 
-
     if (!PyArg_ParseTuple(args,"O|i:join", &cursorsObj, &flags))
         return NULL;
 
@@ -1811,6 +1810,11 @@
 
     length = PyObject_Length(cursorsObj);
     cursors = malloc((length+1) * sizeof(DBC*));
+    if (!cursors) {
+	PyErr_NoMemory();
+	return NULL;
+    }
+
     cursors[length] = NULL;
     for (x=0; x<length; x++) {
         PyObject* item = PySequence_GetItem(cursorsObj, x);
@@ -2622,11 +2626,13 @@
     CHECK_DB_NOT_CLOSED(self);
     if (outFileName)
         outFile = fopen(outFileName, "w");
+	/* XXX(nnorwitz): it should probably be an exception if outFile
+	   can't be opened. */
 
     MYDB_BEGIN_ALLOW_THREADS;
     err = self->db->verify(self->db, fileName, dbName, outFile, flags);
     MYDB_END_ALLOW_THREADS;
-    if (outFileName)
+    if (outFile)
         fclose(outFile);
 
     /* DB.verify acts as a DB handle destructor (like close); this was

Modified: stackless/trunk/Modules/_codecsmodule.c
==============================================================================
--- stackless/trunk/Modules/_codecsmodule.c	(original)
+++ stackless/trunk/Modules/_codecsmodule.c	Mon Aug 21 11:10:05 2006
@@ -192,7 +192,8 @@
 	buf = PyString_AS_STRING (str);
 	len = PyString_GET_SIZE (str);
 	memmove(buf, buf+1, len-2);
-	_PyString_Resize(&str, len-2);
+	if (_PyString_Resize(&str, len-2) < 0)
+		return NULL;
 	
 	return codec_tuple(str, PyString_Size(str));
 }

Modified: stackless/trunk/Modules/_ctypes/_ctypes.c
==============================================================================
--- stackless/trunk/Modules/_ctypes/_ctypes.c	(original)
+++ stackless/trunk/Modules/_ctypes/_ctypes.c	Mon Aug 21 11:10:05 2006
@@ -140,6 +140,31 @@
   accessible fields somehow.
 */
 
+static PyCArgObject *
+StructUnionType_paramfunc(CDataObject *self)
+{
+	PyCArgObject *parg;
+	StgDictObject *stgdict;
+	
+	parg = new_CArgObject();
+	if (parg == NULL)
+		return NULL;
+
+	parg->tag = 'V';
+	stgdict = PyObject_stgdict((PyObject *)self);
+	assert(stgdict); /* Cannot be NULL for structure/union instances */
+	parg->pffi_type = &stgdict->ffi_type_pointer;
+	/* For structure parameters (by value), parg->value doesn't contain the structure
+	   data itself, instead parg->value.p *points* to the structure's data
+	   See also _ctypes.c, function _call_function_pointer().
+	*/
+	parg->value.p = self->b_ptr;
+	parg->size = self->b_size;
+	Py_INCREF(self);
+	parg->obj = (PyObject *)self;
+	return parg;	
+}
+
 static PyObject *
 StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct)
 {
@@ -172,6 +197,8 @@
 	Py_DECREF(result->tp_dict);
 	result->tp_dict = (PyObject *)dict;
 
+	dict->paramfunc = StructUnionType_paramfunc;
+
 	fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
 	if (!fields) {
 		StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
@@ -287,6 +314,7 @@
 static PyObject *
 CDataType_from_param(PyObject *type, PyObject *value)
 {
+	PyObject *as_parameter;
 	if (1 == PyObject_IsInstance(value, type)) {
 		Py_INCREF(value);
 		return value;
@@ -300,7 +328,6 @@
 
 		/* If we got a PyCArgObject, we must check if the object packed in it
 		   is an instance of the type's dict->proto */
-//		if(dict && ob && dict->proto == (PyObject *)ob->ob_type){
 		if(dict && ob
 		   && PyObject_IsInstance(ob, dict->proto)) {
 			Py_INCREF(value);
@@ -330,6 +357,13 @@
 	}
 /* ... and leave the rest */
 #endif
+
+	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+	if (as_parameter) {
+		value = CDataType_from_param(type, as_parameter);
+		Py_DECREF(as_parameter);
+		return value;
+	}
 	PyErr_Format(PyExc_TypeError,
 		     "expected %s instance instead of %s",
 		     ((PyTypeObject *)type)->tp_name,
@@ -540,6 +574,23 @@
 	return 0;
 }
 
+static PyCArgObject *
+PointerType_paramfunc(CDataObject *self)
+{
+	PyCArgObject *parg;
+
+	parg = new_CArgObject();
+	if (parg == NULL)
+		return NULL;
+
+	parg->tag = 'P';
+	parg->pffi_type = &ffi_type_pointer;
+	Py_INCREF(self);
+	parg->obj = (PyObject *)self;
+	parg->value.p = *(void **)self->b_ptr;
+	return parg;
+}
+
 static PyObject *
 PointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
@@ -563,6 +614,7 @@
 	stgdict->align = getentry("P")->pffi_type->alignment;
 	stgdict->length = 1;
 	stgdict->ffi_type_pointer = ffi_type_pointer;
+	stgdict->paramfunc = PointerType_paramfunc;
 
 	proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
 	if (proto && -1 == PointerType_SetProto(stgdict, proto)) {
@@ -640,6 +692,7 @@
  		   the item types are the same.
  		*/
  		StgDictObject *v = PyObject_stgdict(value);
+		assert(v); /* Cannot be NULL for pointer or array objects */
  		if (PyObject_IsSubclass(v->proto, typedict->proto)) {
   			Py_INCREF(value);
   			return value;
@@ -906,6 +959,19 @@
 	return 0;
 }
 
+static PyCArgObject *
+ArrayType_paramfunc(CDataObject *self)
+{
+	PyCArgObject *p = new_CArgObject();
+	if (p == NULL)
+		return NULL;
+	p->tag = 'P';
+	p->pffi_type = &ffi_type_pointer;
+	p->value.p = (char *)self->b_ptr;
+	Py_INCREF(self);
+	p->obj = (PyObject *)self;
+	return p;
+}
 
 static PyObject *
 ArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -961,6 +1027,8 @@
 	Py_INCREF(proto);
 	stgdict->proto = proto;
 
+	stgdict->paramfunc = &ArrayType_paramfunc;
+
 	/* Arrays are passed as pointers to function calls. */
 	stgdict->ffi_type_pointer = ffi_type_pointer;
 
@@ -1055,6 +1123,7 @@
 static PyObject *
 c_wchar_p_from_param(PyObject *type, PyObject *value)
 {
+	PyObject *as_parameter;
 #if (PYTHON_API_VERSION < 1012)
 # error not supported
 #endif
@@ -1067,6 +1136,8 @@
 		struct fielddesc *fd = getentry("Z");
 
 		parg = new_CArgObject();
+		if (parg == NULL)
+			return NULL;
 		parg->pffi_type = &ffi_type_pointer;
 		parg->tag = 'Z';
 		parg->obj = fd->setfunc(&parg->value, value, 0);
@@ -1083,7 +1154,9 @@
 	if (ArrayObject_Check(value) || PointerObject_Check(value)) {
 		/* c_wchar array instance or pointer(c_wchar(...)) */
 		StgDictObject *dt = PyObject_stgdict(value);
-		StgDictObject *dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
+		StgDictObject *dict;
+		assert(dt); /* Cannot be NULL for pointer or array objects */
+		dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
 		if (dict && (dict->setfunc == getentry("u")->setfunc)) {
 			Py_INCREF(value);
 			return value;
@@ -1098,6 +1171,13 @@
 			return value;
 		}
 	}
+
+	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+	if (as_parameter) {
+		value = c_wchar_p_from_param(type, as_parameter);
+		Py_DECREF(as_parameter);
+		return value;
+	}
 	/* XXX better message */
 	PyErr_SetString(PyExc_TypeError,
 			"wrong type");
@@ -1107,6 +1187,7 @@
 static PyObject *
 c_char_p_from_param(PyObject *type, PyObject *value)
 {
+	PyObject *as_parameter;
 #if (PYTHON_API_VERSION < 1012)
 # error not supported
 #endif
@@ -1119,6 +1200,8 @@
 		struct fielddesc *fd = getentry("z");
 
 		parg = new_CArgObject();
+		if (parg == NULL)
+			return NULL;
 		parg->pffi_type = &ffi_type_pointer;
 		parg->tag = 'z';
 		parg->obj = fd->setfunc(&parg->value, value, 0);
@@ -1135,7 +1218,9 @@
 	if (ArrayObject_Check(value) || PointerObject_Check(value)) {
 		/* c_char array instance or pointer(c_char(...)) */
 		StgDictObject *dt = PyObject_stgdict(value);
-		StgDictObject *dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
+		StgDictObject *dict;
+		assert(dt); /* Cannot be NULL for pointer or array objects */
+		dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
 		if (dict && (dict->setfunc == getentry("c")->setfunc)) {
 			Py_INCREF(value);
 			return value;
@@ -1150,6 +1235,13 @@
 			return value;
 		}
 	}
+
+	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+	if (as_parameter) {
+		value = c_char_p_from_param(type, as_parameter);
+		Py_DECREF(as_parameter);
+		return value;
+	}
 	/* XXX better message */
 	PyErr_SetString(PyExc_TypeError,
 			"wrong type");
@@ -1160,6 +1252,7 @@
 c_void_p_from_param(PyObject *type, PyObject *value)
 {
 	StgDictObject *stgd;
+	PyObject *as_parameter;
 #if (PYTHON_API_VERSION < 1012)
 # error not supported
 #endif
@@ -1176,6 +1269,8 @@
 		struct fielddesc *fd = getentry("P");
 
 		parg = new_CArgObject();
+		if (parg == NULL)
+			return NULL;
 		parg->pffi_type = &ffi_type_pointer;
 		parg->tag = 'P';
 		parg->obj = fd->setfunc(&parg->value, value, 0);
@@ -1191,6 +1286,8 @@
 		struct fielddesc *fd = getentry("z");
 
 		parg = new_CArgObject();
+		if (parg == NULL)
+			return NULL;
 		parg->pffi_type = &ffi_type_pointer;
 		parg->tag = 'z';
 		parg->obj = fd->setfunc(&parg->value, value, 0);
@@ -1206,6 +1303,8 @@
 		struct fielddesc *fd = getentry("Z");
 
 		parg = new_CArgObject();
+		if (parg == NULL)
+			return NULL;
 		parg->pffi_type = &ffi_type_pointer;
 		parg->tag = 'Z';
 		parg->obj = fd->setfunc(&parg->value, value, 0);
@@ -1242,6 +1341,8 @@
 		CFuncPtrObject *func;
 		func = (CFuncPtrObject *)value;
 		parg = new_CArgObject();
+		if (parg == NULL)
+			return NULL;
 		parg->pffi_type = &ffi_type_pointer;
 		parg->tag = 'P';
 		Py_INCREF(value);
@@ -1269,6 +1370,13 @@
 			return (PyObject *)parg;
 		}
 	}
+
+	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+	if (as_parameter) {
+		value = c_void_p_from_param(type, as_parameter);
+		Py_DECREF(as_parameter);
+		return value;
+	}
 	/* XXX better message */
 	PyErr_SetString(PyExc_TypeError,
 			"wrong type");
@@ -1355,6 +1463,33 @@
 	return (PyObject *)result;
 }
 
+static PyCArgObject *
+SimpleType_paramfunc(CDataObject *self)
+{
+	StgDictObject *dict;
+	char *fmt;
+	PyCArgObject *parg;
+	struct fielddesc *fd;
+	
+	dict = PyObject_stgdict((PyObject *)self);
+	assert(dict); /* Cannot be NULL for CDataObject instances */
+	fmt = PyString_AsString(dict->proto);
+	assert(fmt);
+
+	fd = getentry(fmt);
+	assert(fd);
+	
+	parg = new_CArgObject();
+	if (parg == NULL)
+		return NULL;
+	
+	parg->tag = fmt[0];
+	parg->pffi_type = fd->pffi_type;
+	Py_INCREF(self);
+	parg->obj = (PyObject *)self;
+	memcpy(&parg->value, self->b_ptr, self->b_size);
+	return parg;	
+}
 
 static PyObject *
 SimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
@@ -1404,6 +1539,8 @@
 	stgdict->size = fmt->pffi_type->size;
 	stgdict->setfunc = fmt->setfunc;
 	stgdict->getfunc = fmt->getfunc;
+
+	stgdict->paramfunc = SimpleType_paramfunc;
 /*
 	if (result->tp_base != &Simple_Type) {
 		stgdict->setfunc = NULL;
@@ -1502,23 +1639,6 @@
 /*
  * This is a *class method*.
  * Convert a parameter into something that ConvParam can handle.
- *
- * This is either an instance of the requested type, a Python integer, or a
- * 'magic' 3-tuple.
- *
- * (These are somewhat related to Martin v. Loewis 'Enhanced Argument Tuples',
- * described in PEP 286.)
- *
- * The tuple must contain
- *
- * - a format character, currently 'ifdqc' are understood
- *   which will inform ConvParam about how to push the argument on the stack.
- *
- * - a corresponding Python object: i - integer, f - float, d - float,
- *   q - longlong, c - integer
- *
- * - any object which can be used to keep the original parameter alive
- *   as long as the tuple lives.
  */
 static PyObject *
 SimpleType_from_param(PyObject *type, PyObject *value)
@@ -1527,6 +1647,7 @@
 	char *fmt;
 	PyCArgObject *parg;
 	struct fielddesc *fd;
+	PyObject *as_parameter;
 
 	/* If the value is already an instance of the requested type,
 	   we can use it as is */
@@ -1552,11 +1673,20 @@
 	parg->tag = fmt[0];
 	parg->pffi_type = fd->pffi_type;
 	parg->obj = fd->setfunc(&parg->value, value, 0);
-	if (parg->obj == NULL) {
-		Py_DECREF(parg);
-		return NULL;
+	if (parg->obj)
+		return (PyObject *)parg;
+	PyErr_Clear();
+	Py_DECREF(parg);
+
+	as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+	if (as_parameter) {
+		value = SimpleType_from_param(type, as_parameter);
+		Py_DECREF(as_parameter);
+		return value;
 	}
-	return (PyObject *)parg;
+	PyErr_SetString(PyExc_TypeError,
+			"wrong type");
+	return NULL;
 }
 
 static PyMethodDef SimpleType_methods[] = {
@@ -1721,6 +1851,23 @@
 
 }
 
+static PyCArgObject *
+CFuncPtrType_paramfunc(CDataObject *self)
+{
+	PyCArgObject *parg;
+	
+	parg = new_CArgObject();
+	if (parg == NULL)
+		return NULL;
+	
+	parg->tag = 'P';
+	parg->pffi_type = &ffi_type_pointer;
+	Py_INCREF(self);
+	parg->obj = (PyObject *)self;
+	parg->value.p = *(void **)self->b_ptr;
+	return parg;	
+}
+
 static PyObject *
 CFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
@@ -1732,6 +1879,8 @@
 	if (!stgdict)
 		return NULL;
 
+	stgdict->paramfunc = CFuncPtrType_paramfunc;
+
 	/* create the new instance (which is a class,
 	   since we are a metatype!) */
 	result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
@@ -1921,6 +2070,7 @@
 CData_clear(CDataObject *self)
 {
 	StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+	assert(dict); /* Cannot be NULL for CDataObject instances */
 	Py_CLEAR(self->b_objects);
 	if ((self->b_needsfree)
 	    && ((size_t)dict->size > sizeof(self->b_value)))
@@ -2218,7 +2368,9 @@
 		StgDictObject *p1, *p2;
 		PyObject *keep;
 		p1 = PyObject_stgdict(value);
+		assert(p1); /* Cannot be NULL for array instances */
 		p2 = PyType_stgdict(type);
+		assert(p2); /* Cannot be NULL for pointer types */
 
 		if (p1->proto != p2->proto) {
 			PyErr_Format(PyExc_TypeError,
@@ -2308,23 +2460,6 @@
   CFuncPtr_Type
 */
 
-static PyObject *
-CFuncPtr_as_parameter(CDataObject *self)
-{
-	PyCArgObject *parg;
-	
-	parg = new_CArgObject();
-	if (parg == NULL)
-		return NULL;
-	
-	parg->tag = 'P';
-	parg->pffi_type = &ffi_type_pointer;
-	Py_INCREF(self);
-	parg->obj = (PyObject *)self;
-	parg->value.p = *(void **)self->b_ptr;
-	return (PyObject *)parg;	
-}
-
 static int
 CFuncPtr_set_errcheck(CFuncPtrObject *self, PyObject *ob)
 {
@@ -2384,7 +2519,7 @@
 		return self->restype;
 	}
 	dict = PyObject_stgdict((PyObject *)self);
-	assert(dict);
+	assert(dict); /* Cannot be NULL for CFuncPtrObject instances */
 	if (dict->restype) {
 		Py_INCREF(dict->restype);
 		return dict->restype;
@@ -2426,7 +2561,7 @@
 		return self->argtypes;
 	}
 	dict = PyObject_stgdict((PyObject *)self);
-	assert(dict);
+	assert(dict); /* Cannot be NULL for CFuncPtrObject instances */
 	if (dict->argtypes) {
 		Py_INCREF(dict->argtypes);
 		return dict->argtypes;
@@ -2444,9 +2579,6 @@
 	{ "argtypes", (getter)CFuncPtr_get_argtypes,
 	  (setter)CFuncPtr_set_argtypes,
 	  "specify the argument types", NULL },
-	{ "_as_parameter_", (getter)CFuncPtr_as_parameter, NULL,
-	  "return a magic value so that this can be converted to a C parameter (readonly)",
-	  NULL },
 	{ NULL, NULL }
 };
 
@@ -2475,6 +2607,8 @@
 	   where n is 0, 4, 8, 12, ..., 128
 	 */
 	mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
+	if (!mangled_name)
+		return NULL;
 	for (i = 0; i < 32; ++i) {
 		sprintf(mangled_name, "_%s@%d", name, i*4);
 		address = (PPROC)GetProcAddress(handle, mangled_name);
@@ -2520,8 +2654,12 @@
 _validate_paramflags(PyTypeObject *type, PyObject *paramflags)
 {
 	int i, len;
-	StgDictObject *dict = PyType_stgdict((PyObject *)type);
-	PyObject *argtypes = dict->argtypes;
+	StgDictObject *dict;
+	PyObject *argtypes;
+
+	dict = PyType_stgdict((PyObject *)type);
+	assert(dict); /* Cannot be NULL. 'type' is a CFuncPtr type. */
+	argtypes = dict->argtypes;
 
 	if (paramflags == NULL || dict->argtypes == NULL)
 		return 1;
@@ -2744,6 +2882,8 @@
 		if (ptr == NULL)
 			return NULL;
 		ob = (CDataObject *)GenericCData_new(type, args, kwds);
+		if (ob == NULL)
+			return NULL;
 		*(void **)ob->b_ptr = ptr;
 		return (PyObject *)ob;
 	}
@@ -2791,6 +2931,8 @@
 		return NULL;
 
 	self = (CFuncPtrObject *)GenericCData_new(type, args, kwds);
+	if (self == NULL)
+		return NULL;
 
 	Py_INCREF(callable);
 	self->callable = callable;
@@ -3129,7 +3271,7 @@
 	int outmask;
 	unsigned int numretvals;
 
-	assert(dict); /* if not, it's a bug */
+	assert(dict); /* Cannot be NULL for CFuncPtrObject instances */
 	restype = self->restype ? self->restype : dict->restype;
 	converters = self->converters ? self->converters : dict->converters;
 	checker = self->checker ? self->checker : dict->checker;
@@ -3349,30 +3491,6 @@
 	return -1;
 }
 
-static PyObject *
-Struct_as_parameter(CDataObject *self)
-{
-	PyCArgObject *parg;
-	StgDictObject *stgdict;
-	
-	parg = new_CArgObject();
-	if (parg == NULL)
-		return NULL;
-
-	parg->tag = 'V';
-	stgdict = PyObject_stgdict((PyObject *)self);
-	parg->pffi_type = &stgdict->ffi_type_pointer;
-	/* For structure parameters (by value), parg->value doesn't contain the structure
-	   data itself, instead parg->value.p *points* to the structure's data
-	   See also _ctypes.c, function _call_function_pointer().
-	*/
-	parg->value.p = self->b_ptr;
-	parg->size = self->b_size;
-	Py_INCREF(self);
-	parg->obj = (PyObject *)self;
-	return (PyObject *)parg;	
-}
-
 static int
 Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
 {
@@ -3447,13 +3565,6 @@
 	return 0;
 }
 
-static PyGetSetDef Struct_getsets[] = {
-	{ "_as_parameter_", (getter)Struct_as_parameter, NULL,
-	  "return a magic value so that this can be converted to a C parameter (readonly)",
-	  NULL },
-	{ NULL, NULL }
-};
-
 static PyTypeObject Struct_Type = {
 	PyObject_HEAD_INIT(NULL)
 	0,
@@ -3485,7 +3596,7 @@
 	0,					/* tp_iternext */
 	0,					/* tp_methods */
 	0,					/* tp_members */
-	Struct_getsets,				/* tp_getset */
+	0,					/* tp_getset */
 	0,					/* tp_base */
 	0,					/* tp_dict */
 	0,					/* tp_descr_get */
@@ -3528,7 +3639,7 @@
 	0,					/* tp_iternext */
 	0,					/* tp_methods */
 	0,					/* tp_members */
-	Struct_getsets,				/* tp_getset */
+	0,					/* tp_getset */
 	0,					/* tp_base */
 	0,					/* tp_dict */
 	0,					/* tp_descr_get */
@@ -3581,7 +3692,7 @@
 	}
 
 	stgdict = PyObject_stgdict((PyObject *)self);
-	assert(stgdict);
+	assert(stgdict); /* Cannot be NULL for array instances */
 	/* Would it be clearer if we got the item size from
 	   stgdict->proto's stgdict?
 	*/
@@ -3612,6 +3723,7 @@
 	len = ihigh - ilow;
 
 	stgdict = PyObject_stgdict((PyObject *)self);
+	assert(stgdict); /* Cannot be NULL for array object instances */
 	proto = stgdict->proto;
 	itemdict = PyType_stgdict(proto);
 	if (itemdict->getfunc == getentry("c")->getfunc) {
@@ -3650,6 +3762,7 @@
 	}
 	
 	stgdict = PyObject_stgdict((PyObject *)self);
+	assert(stgdict); /* Cannot be NULL for array object instances */
 	if (index < 0 || index >= stgdict->length) {
 		PyErr_SetString(PyExc_IndexError,
 				"invalid index");
@@ -3726,26 +3839,6 @@
 	0,					/* sq_inplace_repeat; */
 };
 
-static PyObject *
-Array_as_parameter(CDataObject *self)
-{
-	PyCArgObject *p = new_CArgObject();
-	if (p == NULL)
-		return NULL;
-	p->tag = 'P';
-	p->pffi_type = &ffi_type_pointer;
-	p->value.p = (char *)self->b_ptr;
-	Py_INCREF(self);
-	p->obj = (PyObject *)self;
-	return (PyObject *)p;
-}
-
-static PyGetSetDef Array_getsets[] = {
-	{ "_as_parameter_", (getter)Array_as_parameter,
-	  (setter)NULL, "convert to a parameter", NULL },
-	{ NULL },
-};
-
 PyTypeObject Array_Type = {
 	PyObject_HEAD_INIT(NULL)
 	0,
@@ -3777,7 +3870,7 @@
 	0,					/* tp_iternext */
 	0,					/* tp_methods */
 	0,					/* tp_members */
-	Array_getsets,				/* tp_getset */
+	0,					/* tp_getset */
 	0,					/* tp_base */
 	0,					/* tp_dict */
 	0,					/* tp_descr_get */
@@ -3861,6 +3954,7 @@
 	PyObject *result;
 	StgDictObject *dict = PyObject_stgdict((PyObject *)self);
 
+	assert(dict); /* Cannot be NULL for CDataObject instances */
 	assert(dict->setfunc);
 	result = dict->setfunc(self->b_ptr, value, dict->size);
 	if (!result)
@@ -3886,40 +3980,14 @@
 {
 	StgDictObject *dict;
 	dict = PyObject_stgdict((PyObject *)self);
+	assert(dict); /* Cannot be NULL for CDataObject instances */
 	assert(dict->getfunc);
-	dict = PyObject_stgdict((PyObject *)self);
 	return dict->getfunc(self->b_ptr, self->b_size);
 }
 
-static PyObject *
-Simple_as_parameter(CDataObject *self)
-{
-	StgDictObject *dict = PyObject_stgdict((PyObject *)self);
-	char *fmt = PyString_AsString(dict->proto);
-	PyCArgObject *parg;
-	struct fielddesc *fd;
-	
-	fd = getentry(fmt);
-	assert(fd);
-	
-	parg = new_CArgObject();
-	if (parg == NULL)
-		return NULL;
-	
-	parg->tag = fmt[0];
-	parg->pffi_type = fd->pffi_type;
-	Py_INCREF(self);
-	parg->obj = (PyObject *)self;
-	memcpy(&parg->value, self->b_ptr, self->b_size);
-	return (PyObject *)parg;	
-}
-
 static PyGetSetDef Simple_getsets[] = {
 	{ "value", (getter)Simple_get_value, (setter)Simple_set_value,
 	  "current value", NULL },
-	{ "_as_parameter_", (getter)Simple_as_parameter, NULL,
-	  "return a magic value so that this can be converted to a C parameter (readonly)",
-	  NULL },
 	{ NULL, NULL }
 };
 
@@ -4086,11 +4154,10 @@
 	}
 
 	stgdict = PyObject_stgdict((PyObject *)self);
-	assert(stgdict);
-	assert(stgdict->proto);
+	assert(stgdict); /* Cannot be NULL for pointer object instances */
 	
 	proto = stgdict->proto;
-	/* XXXXXX MAKE SURE PROTO IS NOT NULL! */
+	assert(proto);
 	itemdict = PyType_stgdict(proto);
 	size = itemdict->size;
 	offset = index * itemdict->size;
@@ -4121,11 +4188,11 @@
 	}
 	
 	stgdict = PyObject_stgdict((PyObject *)self);
-	assert(stgdict);
-	assert(stgdict->proto);
+	assert(stgdict); /* Cannot be NULL fr pointer instances */
 
 	proto = stgdict->proto;
-	/* XXXXXX MAKE SURE PROTO IS NOT NULL! */
+	assert(proto);
+
 	itemdict = PyType_stgdict(proto);
 	size = itemdict->size;
 	offset = index * itemdict->size;
@@ -4146,7 +4213,7 @@
 	}
 
 	stgdict = PyObject_stgdict((PyObject *)self);
-	assert(stgdict);
+	assert(stgdict); /* Cannot be NULL fr pointer instances */
 	return CData_FromBaseObj(stgdict->proto,
 				 (PyObject *)self, 0,
 				 *(void **)self->b_ptr);
@@ -4165,7 +4232,7 @@
 		return -1;
 	}
 	stgdict = PyObject_stgdict((PyObject *)self);
-	/* should have been catched in Pointer_new() */
+	assert(stgdict); /* Cannot be NULL fr pointer instances */
 	assert(stgdict->proto);
 	if (!CDataObject_Check(value) 
 	    || 0 == PyObject_IsInstance(value, stgdict->proto)) {
@@ -4194,30 +4261,10 @@
 	return KeepRef(self, 0, keep);
 }
 
-static PyObject *
-Pointer_as_parameter(CDataObject *self)
-{
-	PyCArgObject *parg;
-
-	parg = new_CArgObject();
-	if (parg == NULL)
-		return NULL;
-
-	parg->tag = 'P';
-	parg->pffi_type = &ffi_type_pointer;
-	Py_INCREF(self);
-	parg->obj = (PyObject *)self;
-	parg->value.p = *(void **)self->b_ptr;
-	return (PyObject *)parg;
-}
-
 static PyGetSetDef Pointer_getsets[] = {
 	{ "contents", (getter)Pointer_get_contents,
 	  (setter)Pointer_set_contents,
 	  "the object this pointer points to (read-write)", NULL },
-	{ "_as_parameter_", (getter)Pointer_as_parameter, NULL,
-	  "return a magic value so that this can be converted to a C parameter (readonly)",
-	  NULL },
 	{ NULL, NULL }
 };
 
@@ -4261,8 +4308,11 @@
 	len = ihigh - ilow;
 
 	stgdict = PyObject_stgdict((PyObject *)self);
+	assert(stgdict); /* Cannot be NULL fr pointer instances */
 	proto = stgdict->proto;
+	assert(proto);
 	itemdict = PyType_stgdict(proto);
+	assert(itemdict);
 	if (itemdict->getfunc == getentry("c")->getfunc) {
 		char *ptr = *(char **)self->b_ptr;
 		return PyString_FromStringAndSize(ptr + ilow, len);
@@ -4678,7 +4728,7 @@
 #endif
 	PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
 	PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI));
-	PyModule_AddStringConstant(m, "__version__", "1.0.0");
+	PyModule_AddStringConstant(m, "__version__", "1.0.1");
 
 	PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
 	PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));

Modified: stackless/trunk/Modules/_ctypes/_ctypes_test.c
==============================================================================
--- stackless/trunk/Modules/_ctypes/_ctypes_test.c	(original)
+++ stackless/trunk/Modules/_ctypes/_ctypes_test.c	Mon Aug 21 11:10:05 2006
@@ -197,18 +197,6 @@
 
 #endif
 
-EXPORT(int) _testfunc_ppp(char ***p)
-{
-	static char message[] = "Hello, World";
-	if (p) {
-		*p = (char **)malloc(sizeof(char *));
-		printf("malloc returned %p\n", *p);
-		**p = message;
-		return 1;
-	}
-	return 0;
-}
-
 typedef struct {
 	char *name;
 	char *value;

Modified: stackless/trunk/Modules/_ctypes/callbacks.c
==============================================================================
--- stackless/trunk/Modules/_ctypes/callbacks.c	(original)
+++ stackless/trunk/Modules/_ctypes/callbacks.c	Mon Aug 21 11:10:05 2006
@@ -205,7 +205,7 @@
 
 	result = PyObject_CallObject(callable, arglist);
 	CHECK("'calling callback function'", result);
-	if ((restype != &ffi_type_void) && result && result != Py_None) {
+	if ((restype != &ffi_type_void) && result) {
 		PyObject *keep;
 		assert(setfunc);
 #ifdef WORDS_BIGENDIAN
@@ -225,13 +225,13 @@
 		   itself knows how to manage the refcount of these objects.
 		*/
 		if (keep == NULL) /* Could not convert callback result. */
-			PyErr_WriteUnraisable(Py_None);
+			PyErr_WriteUnraisable(callable);
 		else if (keep == Py_None) /* Nothing to keep */
 			Py_DECREF(keep);
 		else if (setfunc != getentry("O")->setfunc) {
 			if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
 					     "memory leak in callback function."))
-				PyErr_WriteUnraisable(Py_None);
+				PyErr_WriteUnraisable(callable);
 		}
 	}
 	Py_XDECREF(result);

Modified: stackless/trunk/Modules/_ctypes/callproc.c
==============================================================================
--- stackless/trunk/Modules/_ctypes/callproc.c	(original)
+++ stackless/trunk/Modules/_ctypes/callproc.c	Mon Aug 21 11:10:05 2006
@@ -465,7 +465,21 @@
  */
 static int ConvParam(PyObject *obj, int index, struct argument *pa)
 {
+	StgDictObject *dict;
 	pa->keep = NULL; /* so we cannot forget it later */
+
+	dict = PyObject_stgdict(obj);
+	if (dict) {
+		PyCArgObject *carg;
+		assert(dict->paramfunc);
+		/* If it has an stgdict, it is a CDataObject */
+		carg = dict->paramfunc((CDataObject *)obj);
+		pa->ffi_type = carg->pffi_type;
+		memcpy(&pa->value, &carg->value, sizeof(pa->value));
+		pa->keep = (PyObject *)carg;
+		return 0;
+	}
+
 	if (PyCArg_CheckExact(obj)) {
 		PyCArgObject *carg = (PyCArgObject *)obj;
 		pa->ffi_type = carg->pffi_type;
@@ -548,25 +562,12 @@
 		   as parameters (they have to expose the '_as_parameter_'
 		   attribute)
 		*/
-		if (arg == 0) {
-			PyErr_Format(PyExc_TypeError,
-				     "Don't know how to convert parameter %d", index);
-			return -1;
+		if (arg) {
+			int result;
+			result = ConvParam(arg, index, pa);
+			Py_DECREF(arg);
+			return result;
 		}
-		if (PyCArg_CheckExact(arg)) {
-			PyCArgObject *carg = (PyCArgObject *)arg;
-			pa->ffi_type = carg->pffi_type;
-			memcpy(&pa->value, &carg->value, sizeof(pa->value));
-			pa->keep = arg;
-			return 0;
-		}
-		if (PyInt_Check(arg)) {
-			pa->ffi_type = &ffi_type_sint;
-			pa->value.i = PyInt_AS_LONG(arg);
-			pa->keep = arg;
-			return 0;
-		}
-		Py_DECREF(arg);
 		PyErr_Format(PyExc_TypeError,
 			     "Don't know how to convert parameter %d", index);
 		return -1;
@@ -915,6 +916,10 @@
 #endif
 
 	args = (struct argument *)alloca(sizeof(struct argument) * argcount);
+	if (!args) {
+		PyErr_NoMemory();
+		return NULL;
+	}
 	memset(args, 0, sizeof(struct argument) * argcount);
 	argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
 #ifdef MS_WIN32
@@ -968,6 +973,10 @@
 
 	avalues = (void **)alloca(sizeof(void *) * argcount);
 	atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
+	if (!resbuf || !avalues || !atypes) {
+		PyErr_NoMemory();
+		goto cleanup;
+	}
 	for (i = 0; i < argcount; ++i) {
 		atypes[i] = args[i].ffi_type;
 		if (atypes[i]->type == FFI_TYPE_STRUCT)
@@ -1068,6 +1077,11 @@
 		return NULL;
 #ifdef _UNICODE
 	name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
+	if (!name) {
+		PyErr_NoMemory();
+		return NULL;
+	}
+
 	{
 		int r;
 		char *aname = PyString_AsString(nameobj);

Modified: stackless/trunk/Modules/_ctypes/cfield.c
==============================================================================
--- stackless/trunk/Modules/_ctypes/cfield.c	(original)
+++ stackless/trunk/Modules/_ctypes/cfield.c	Mon Aug 21 11:10:05 2006
@@ -105,6 +105,12 @@
 		StgDictObject *idict;
 		if (adict && adict->proto) {
 			idict = PyType_stgdict(adict->proto);
+			if (!idict) {
+				PyErr_SetString(PyExc_TypeError,
+						"has no _stginfo_");
+				Py_DECREF(self);
+				return NULL;
+			}
 			if (idict->getfunc == getentry("c")->getfunc) {
 				struct fielddesc *fd = getentry("s");
 				getfunc = fd->getfunc;
@@ -1094,7 +1100,7 @@
 		if (!PyErr_Occurred())
 			/* Set an error if not yet set */
 			PyErr_SetString(PyExc_ValueError,
-					"PyObject is NULL?");
+					"PyObject is NULL");
 		return NULL;
 	}
 	Py_INCREF(ob);

Modified: stackless/trunk/Modules/_ctypes/ctypes.h
==============================================================================
--- stackless/trunk/Modules/_ctypes/ctypes.h	(original)
+++ stackless/trunk/Modules/_ctypes/ctypes.h	Mon Aug 21 11:10:05 2006
@@ -23,9 +23,11 @@
 #define PY_LONG_LONG LONG_LONG
 #endif
 
+typedef struct tagPyCArgObject PyCArgObject;
 typedef struct tagCDataObject CDataObject;
 typedef PyObject *(* GETFUNC)(void *, unsigned size);
 typedef PyObject *(* SETFUNC)(void *, PyObject *value, unsigned size);
+typedef PyCArgObject *(* PARAMFUNC)(CDataObject *obj);
 
 /* A default buffer in CDataObject, which can be used for small C types.  If
 this buffer is too small, PyMem_Malloc will be called to create a larger one,
@@ -205,6 +207,7 @@
 	PyObject *proto;	/* Only for Pointer/ArrayObject */
 	SETFUNC setfunc;	/* Only for simple objects */
 	GETFUNC getfunc;	/* Only for simple objects */
+	PARAMFUNC paramfunc;
 
 	/* Following fields only used by CFuncPtrType_Type instances */
 	PyObject *argtypes;	/* tuple of CDataObjects */
@@ -283,7 +286,7 @@
 
 #define DICTFLAG_FINAL 0x1000
 
-typedef struct {
+struct tagPyCArgObject {
 	PyObject_HEAD
 	ffi_type *pffi_type;
 	char tag;
@@ -302,7 +305,7 @@
 	} value;
 	PyObject *obj;
 	int size; /* for the 'V' tag */
-} PyCArgObject;
+};
 
 extern PyTypeObject PyCArg_Type;
 extern PyCArgObject *new_CArgObject(void);

Modified: stackless/trunk/Modules/_ctypes/libffi/configure
==============================================================================
--- stackless/trunk/Modules/_ctypes/libffi/configure	(original)
+++ stackless/trunk/Modules/_ctypes/libffi/configure	Mon Aug 21 11:10:05 2006
@@ -3470,6 +3470,7 @@
 
 TARGETDIR="unknown"
 case "$host" in
+x86_64-*-openbsd*) TARGET=X86_64; TARGETDIR=x86;;
 mips*-*-openbsd*) TARGET=MIPS; TARGETDIR=mips;;
 sparc-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;;
 sparc64-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;;

Modified: stackless/trunk/Modules/_ctypes/libffi/configure.ac
==============================================================================
--- stackless/trunk/Modules/_ctypes/libffi/configure.ac	(original)
+++ stackless/trunk/Modules/_ctypes/libffi/configure.ac	Mon Aug 21 11:10:05 2006
@@ -21,6 +21,7 @@
 
 TARGETDIR="unknown"
 case "$host" in
+x86_64-*-openbsd*) TARGET=X86_64; TARGETDIR=x86;;
 mips*-*-openbsd*) TARGET=MIPS; TARGETDIR=mips;;
 sparc-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;;
 sparc64-*-openbsd*) TARGET=SPARC; TARGETDIR=sparc;;

Modified: stackless/trunk/Modules/_ctypes/libffi/fficonfig.py.in
==============================================================================
--- stackless/trunk/Modules/_ctypes/libffi/fficonfig.py.in	(original)
+++ stackless/trunk/Modules/_ctypes/libffi/fficonfig.py.in	Mon Aug 21 11:10:05 2006
@@ -43,6 +43,3 @@
 ffi_sources = [os.path.join('@srcdir@', f) for f in ffi_sources]
 
 ffi_cflags = '@CFLAGS@'
-# I think this may no longer be needed:
-if sys.platform == "openbsd3":
-    ffi_cflags += " -fno-stack-protector"

Modified: stackless/trunk/Modules/_cursesmodule.c
==============================================================================
--- stackless/trunk/Modules/_cursesmodule.c	(original)
+++ stackless/trunk/Modules/_cursesmodule.c	Mon Aug 21 11:10:05 2006
@@ -1784,7 +1784,6 @@
 PyCurses_InitScr(PyObject *self)
 {
   WINDOW *win;
-  PyObject *nlines, *cols;
 
   if (initialised == TRUE) {
     wrefresh(stdscr);
@@ -1803,7 +1802,12 @@
 /* This was moved from initcurses() because it core dumped on SGI,
    where they're not defined until you've called initscr() */
 #define SetDictInt(string,ch) \
-	PyDict_SetItemString(ModDict,string,PyInt_FromLong((long) (ch)));
+    do {							\
+	PyObject *o = PyInt_FromLong((long) (ch));		\
+	if (o && PyDict_SetItemString(ModDict, string, o) == 0)	{ \
+	    Py_DECREF(o);					\
+	}							\
+    } while (0)
 
 	/* Here are some graphic symbols you can use */
         SetDictInt("ACS_ULCORNER",      (ACS_ULCORNER));
@@ -1872,12 +1876,8 @@
 	SetDictInt("ACS_STERLING",      (ACS_STERLING));
 #endif
 
-  nlines = PyInt_FromLong((long) LINES);
-  PyDict_SetItemString(ModDict, "LINES", nlines);
-  Py_DECREF(nlines);
-  cols = PyInt_FromLong((long) COLS);
-  PyDict_SetItemString(ModDict, "COLS", cols);
-  Py_DECREF(cols);
+  SetDictInt("LINES", LINES);
+  SetDictInt("COLS", COLS);
 
   return (PyObject *)PyCursesWindow_New(win);
 }
@@ -2554,6 +2554,8 @@
 
 	/* Add some symbolic constants to the module */
 	d = PyModule_GetDict(m);
+	if (d == NULL)
+		return;
 	ModDict = d; /* For PyCurses_InitScr to use later */
 
 	/* Add a CObject for the C API */
@@ -2667,6 +2669,10 @@
 	    if (strncmp(key_n,"KEY_F(",6)==0) {
 	      char *p1, *p2;
 	      key_n2 = malloc(strlen(key_n)+1);
+	      if (!key_n2) {
+		PyErr_NoMemory();
+		break;
+              }
 	      p1 = key_n;
 	      p2 = key_n2;
 	      while (*p1) {
@@ -2679,7 +2685,7 @@
 	      *p2 = (char)0;
 	    } else
 	      key_n2 = key_n;
-	    PyDict_SetItemString(d,key_n2,PyInt_FromLong((long) key));
+	    SetDictInt(key_n2,key);
 	    if (key_n2 != key_n)
 	      free(key_n2);
 	  }

Modified: stackless/trunk/Modules/_elementtree.c
==============================================================================
--- stackless/trunk/Modules/_elementtree.c	(original)
+++ stackless/trunk/Modules/_elementtree.c	Mon Aug 21 11:10:05 2006
@@ -48,7 +48,7 @@
 
 #include "Python.h"
 
-#define VERSION "1.0.6-snapshot"
+#define VERSION "1.0.6"
 
 /* -------------------------------------------------------------------- */
 /* configuration */
@@ -809,7 +809,7 @@
             PyObject* text = element_get_text(item);
             if (text == Py_None)
                 return PyString_FromString("");
-            Py_INCREF(text);
+            Py_XINCREF(text);
             return text;
         }
     }
@@ -1599,6 +1599,10 @@
 treebuilder_handle_data(TreeBuilderObject* self, PyObject* data)
 {
     if (!self->data) {
+        if (self->last == (ElementObject*) Py_None) {
+            /* ignore calls to data before the first call to start */
+            Py_RETURN_NONE;
+        }
         /* store the first item as is */
         Py_INCREF(data); self->data = data;
     } else {

Modified: stackless/trunk/Modules/_hotshot.c
==============================================================================
--- stackless/trunk/Modules/_hotshot.c	(original)
+++ stackless/trunk/Modules/_hotshot.c	Mon Aug 21 11:10:05 2006
@@ -313,6 +313,11 @@
         return err;
 
     buf = (char *)malloc(len);
+    if (!buf) {
+	PyErr_NoMemory();
+	return ERR_EXCEPTION;
+    }
+
     for (i=0; i < len; i++) {
         ch = fgetc(self->logfp);
 	buf[i] = ch;

Modified: stackless/trunk/Modules/_sre.c
==============================================================================
--- stackless/trunk/Modules/_sre.c	(original)
+++ stackless/trunk/Modules/_sre.c	Mon Aug 21 11:10:05 2006
@@ -1166,6 +1166,9 @@
 
             /* install new repeat context */
             ctx->u.rep = (SRE_REPEAT*) PyObject_MALLOC(sizeof(*ctx->u.rep));
+            /* XXX(nnorwitz): anything else we need to do on error? */
+            if (!ctx->u.rep)
+                RETURN_FAILURE;
             ctx->u.rep->count = -1;
             ctx->u.rep->pattern = ctx->pattern;
             ctx->u.rep->prev = state->repeat;

Modified: stackless/trunk/Modules/_struct.c
==============================================================================
--- stackless/trunk/Modules/_struct.c	(original)
+++ stackless/trunk/Modules/_struct.c	Mon Aug 21 11:10:05 2006
@@ -31,6 +31,17 @@
 static PyObject *pyint_zero = NULL;
 #endif
 
+/* If PY_STRUCT_FLOAT_COERCE is defined, the struct module will allow float
+   arguments for integer formats with a warning for backwards
+   compatibility. */
+
+#define PY_STRUCT_FLOAT_COERCE 1
+
+#ifdef PY_STRUCT_FLOAT_COERCE
+#define FLOAT_COERCE "integer argument expected, got float"
+#endif
+
+
 /* The translation function for each format character is table driven */
 typedef struct _formatdef {
 	char format;
@@ -135,6 +146,21 @@
 {
 	long x = PyInt_AsLong(v);
 	if (x == -1 && PyErr_Occurred()) {
+#ifdef PY_STRUCT_FLOAT_COERCE
+		if (PyFloat_Check(v)) {
+			PyObject *o;
+			int res;
+			PyErr_Clear();
+			if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
+				return -1;
+			o = PyNumber_Int(v);
+			if (o == NULL)
+				return -1;
+			res = get_long(o, p);
+			Py_DECREF(o);
+			return res;
+		}
+#endif
 		if (PyErr_ExceptionMatches(PyExc_TypeError))
 			PyErr_SetString(StructError,
 					"required argument is not an integer");
@@ -225,6 +251,21 @@
 			PyObject *wrapped;
 			long x;
 			PyErr_Clear();
+#ifdef PY_STRUCT_FLOAT_COERCE
+			if (PyFloat_Check(v)) {
+				PyObject *o;
+				int res;
+				PyErr_Clear();
+				if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
+					return -1;
+				o = PyNumber_Int(v);
+				if (o == NULL)
+					return -1;
+				res = get_wrapped_long(o, p);
+				Py_DECREF(o);
+				return res;
+			}
+#endif
 			if (PyErr_WarnEx(PyExc_DeprecationWarning, INT_OVERFLOW, 2) < 0)
 				return -1;
 			wrapped = PyNumber_And(v, pylong_ulong_mask);
@@ -249,6 +290,21 @@
 	if (x == -1 && PyErr_Occurred()) {
 		PyObject *wrapped;
 		PyErr_Clear();
+#ifdef PY_STRUCT_FLOAT_COERCE
+		if (PyFloat_Check(v)) {
+			PyObject *o;
+			int res;
+			PyErr_Clear();
+			if (PyErr_WarnEx(PyExc_DeprecationWarning, FLOAT_COERCE, 2) < 0)
+				return -1;
+			o = PyNumber_Int(v);
+			if (o == NULL)
+				return -1;
+			res = get_wrapped_ulong(o, p);
+			Py_DECREF(o);
+			return res;
+		}
+#endif
 		wrapped = PyNumber_And(v, pylong_ulong_mask);
 		if (wrapped == NULL)
 			return -1;
@@ -1815,4 +1871,8 @@
 #ifdef PY_STRUCT_OVERFLOW_MASKING
 	PyModule_AddIntConstant(m, "_PY_STRUCT_OVERFLOW_MASKING", 1);
 #endif
+#ifdef PY_STRUCT_FLOAT_COERCE
+	PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
+#endif
+
 }

Modified: stackless/trunk/Modules/_testcapimodule.c
==============================================================================
--- stackless/trunk/Modules/_testcapimodule.c	(original)
+++ stackless/trunk/Modules/_testcapimodule.c	Mon Aug 21 11:10:05 2006
@@ -706,6 +706,13 @@
 #undef CHECK_1_FORMAT
 }
 
+/* This is here to provide a docstring for test_descr. */
+static PyObject *
+test_with_docstring(PyObject *self)
+{
+	Py_RETURN_NONE;
+}
+
 static PyMethodDef TestMethods[] = {
 	{"raise_exception",	raise_exception,		 METH_VARARGS},
 	{"test_config",		(PyCFunction)test_config,	 METH_NOARGS},
@@ -716,6 +723,8 @@
 	{"test_k_code",		(PyCFunction)test_k_code,	 METH_NOARGS},
 	{"test_null_strings",	(PyCFunction)test_null_strings,	 METH_NOARGS},
 	{"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
+	{"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
+	 PyDoc_STR("This is a pretty normal docstring.")},
 
 	{"getargs_tuple",	getargs_tuple,			 METH_VARARGS},
 	{"getargs_b",		getargs_b,			 METH_VARARGS},

Modified: stackless/trunk/Modules/_tkinter.c
==============================================================================
--- stackless/trunk/Modules/_tkinter.c	(original)
+++ stackless/trunk/Modules/_tkinter.c	Mon Aug 21 11:10:05 2006
@@ -2493,8 +2493,10 @@
 	}
 
 	v = Tktt_New(func);
-	v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
-					  (ClientData)v);
+	if (v) {
+		v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
+						  (ClientData)v);
+	}
 
 	return (PyObject *) v;
 }

Modified: stackless/trunk/Modules/arraymodule.c
==============================================================================
--- stackless/trunk/Modules/arraymodule.c	(original)
+++ stackless/trunk/Modules/arraymodule.c	Mon Aug 21 11:10:05 2006
@@ -702,6 +702,8 @@
 			/* Special case "a[i:j] = a" -- copy b first */
 			int ret;
 			v = array_slice(b, 0, n);
+			if (!v)
+				return -1;
 			ret = array_ass_slice(a, ilow, ihigh, v);
 			Py_DECREF(v);
 			return ret;
@@ -1570,14 +1572,11 @@
 	return s;
 }
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
-
 static PyObject*
 array_subscr(arrayobject* self, PyObject* item)
 {
-	PyNumberMethods *nb = item->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(item);
+	if (PyIndex_Check(item)) {
+		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 		if (i==-1 && PyErr_Occurred()) {
 			return NULL;
 		}
@@ -1625,9 +1624,8 @@
 static int
 array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
 {
-	PyNumberMethods *nb = item->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(item);
+	if (PyIndex_Check(item)) {
+		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 		if (i==-1 && PyErr_Occurred()) 
 			return -1;
 		if (i < 0)
@@ -1708,6 +1706,8 @@
 			if (self == av) { 
 				value = array_slice(av, 0, av->ob_size);
 				av = (arrayobject*)value;
+				if (!av)
+					return -1;
 			} 
 			else {
 				Py_INCREF(value);

Modified: stackless/trunk/Modules/bz2module.c
==============================================================================
--- stackless/trunk/Modules/bz2module.c	(original)
+++ stackless/trunk/Modules/bz2module.c	Mon Aug 21 11:10:05 2006
@@ -812,12 +812,12 @@
 		case MODE_CLOSED:
 			PyErr_SetString(PyExc_ValueError,
 					"I/O operation on closed file");
-			goto cleanup;;
+			goto cleanup;
 
 		default:
 			PyErr_SetString(PyExc_IOError,
 					"file is not ready for writing");
-			goto cleanup;;
+			goto cleanup;
 	}
 
 	self->f_softspace = 0;
@@ -861,6 +861,21 @@
 	int bzerror;
 
 	ACQUIRE_LOCK(self);
+	switch (self->mode) {
+		case MODE_WRITE:
+			break;
+
+		case MODE_CLOSED:
+			PyErr_SetString(PyExc_ValueError,
+					"I/O operation on closed file");
+			goto error;
+
+		default:
+			PyErr_SetString(PyExc_IOError,
+					"file is not ready for writing");
+			goto error;
+	}
+
 	islist = PyList_Check(seq);
 	if  (!islist) {
 		iter = PyObject_GetIter(seq);

Modified: stackless/trunk/Modules/collectionsmodule.c
==============================================================================
--- stackless/trunk/Modules/collectionsmodule.c	(original)
+++ stackless/trunk/Modules/collectionsmodule.c	Mon Aug 21 11:10:05 2006
@@ -211,6 +211,7 @@
 		PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
 		return NULL;
 	}
+	assert(deque->leftblock != NULL);
 	item = deque->leftblock->data[deque->leftindex];
 	deque->leftindex++;
 	deque->len--;
@@ -226,7 +227,6 @@
 		} else {
 			assert(deque->leftblock != deque->rightblock);
 			prevblock = deque->leftblock->rightlink;
-			assert(deque->leftblock != NULL);
 			PyMem_Free(deque->leftblock);
 			assert(prevblock != NULL);
 			prevblock->leftlink = NULL;

Modified: stackless/trunk/Modules/expat/xmlparse.c
==============================================================================
--- stackless/trunk/Modules/expat/xmlparse.c	(original)
+++ stackless/trunk/Modules/expat/xmlparse.c	Mon Aug 21 11:10:05 2006
@@ -2795,6 +2795,8 @@
         unsigned long uriHash = 0;
         ((XML_Char *)s)[-1] = 0;  /* clear flag */
         id = (ATTRIBUTE_ID *)lookup(&dtd->attributeIds, s, 0);
+        if (!id)
+          return XML_ERROR_NO_MEMORY;
         b = id->prefix->binding;
         if (!b)
           return XML_ERROR_UNBOUND_PREFIX;
@@ -5340,6 +5342,8 @@
             return NULL;
           id->prefix = (PREFIX *)lookup(&dtd->prefixes, poolStart(&dtd->pool),
                                         sizeof(PREFIX));
+          if (!id->prefix)
+            return NULL;
           if (id->prefix->name == poolStart(&dtd->pool))
             poolFinish(&dtd->pool);
           else

Modified: stackless/trunk/Modules/mmapmodule.c
==============================================================================
--- stackless/trunk/Modules/mmapmodule.c	(original)
+++ stackless/trunk/Modules/mmapmodule.c	Mon Aug 21 11:10:05 2006
@@ -808,8 +808,6 @@
 };
 
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
-
 /* extract the map size from the given PyObject
 
    Returns -1 on error, with an appropriate Python exception raised. On
@@ -817,31 +815,19 @@
 static Py_ssize_t
 _GetMapSize(PyObject *o)
 {
-	PyNumberMethods *nb = o->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(o) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(o);
+	if (PyIndex_Check(o)) {
+		Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
 		if (i==-1 && PyErr_Occurred()) 
 			return -1;
-		if (i < 0)
-			goto onnegoverflow;
-		if (i==PY_SSIZE_T_MAX)
-			goto onposoverflow;
+		if (i < 0) {	 
+			PyErr_SetString(PyExc_OverflowError,
+					"memory mapped size must be positive");
+			return -1;
+		}
 		return i;
 	}
-	else {
-		PyErr_SetString(PyExc_TypeError,
-				"map size must be an integral value");
-		return -1;
-	}
-
-  onnegoverflow:
-	PyErr_SetString(PyExc_OverflowError,
-			"memory mapped size must be positive");
-	return -1;
 
-  onposoverflow:
-	PyErr_SetString(PyExc_OverflowError,
-			"memory mapped size is too large (limited by C int)");
+	PyErr_SetString(PyExc_TypeError, "map size must be an integral value");
 	return -1;
 }
 
@@ -1140,6 +1126,15 @@
 	{NULL,		NULL}	     /* Sentinel */
 };
 
+static void
+setint(PyObject *d, const char *name, long value)
+{
+	PyObject *o = PyInt_FromLong(value);
+	if (o && PyDict_SetItemString(d, name, o) == 0) {
+		Py_DECREF(o);
+	}
+}
+
 PyMODINIT_FUNC
 	initmmap(void)
 {
@@ -1152,47 +1147,40 @@
 	if (module == NULL)
 		return;
 	dict = PyModule_GetDict(module);
+	if (!dict)
+		return;
 	mmap_module_error = PyExc_EnvironmentError;
-	Py_INCREF(mmap_module_error);
 	PyDict_SetItemString(dict, "error", mmap_module_error);
 #ifdef PROT_EXEC
-	PyDict_SetItemString(dict, "PROT_EXEC", PyInt_FromLong(PROT_EXEC) );
+	setint(dict, "PROT_EXEC", PROT_EXEC);
 #endif
 #ifdef PROT_READ
-	PyDict_SetItemString(dict, "PROT_READ", PyInt_FromLong(PROT_READ) );
+	setint(dict, "PROT_READ", PROT_READ);
 #endif
 #ifdef PROT_WRITE
-	PyDict_SetItemString(dict, "PROT_WRITE", PyInt_FromLong(PROT_WRITE) );
+	setint(dict, "PROT_WRITE", PROT_WRITE);
 #endif
 
 #ifdef MAP_SHARED
-	PyDict_SetItemString(dict, "MAP_SHARED", PyInt_FromLong(MAP_SHARED) );
+	setint(dict, "MAP_SHARED", MAP_SHARED);
 #endif
 #ifdef MAP_PRIVATE
-	PyDict_SetItemString(dict, "MAP_PRIVATE",
-			     PyInt_FromLong(MAP_PRIVATE) );
+	setint(dict, "MAP_PRIVATE", MAP_PRIVATE);
 #endif
 #ifdef MAP_DENYWRITE
-	PyDict_SetItemString(dict, "MAP_DENYWRITE",
-			     PyInt_FromLong(MAP_DENYWRITE) );
+	setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE);
 #endif
 #ifdef MAP_EXECUTABLE
-	PyDict_SetItemString(dict, "MAP_EXECUTABLE",
-			     PyInt_FromLong(MAP_EXECUTABLE) );
+	setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE);
 #endif
 #ifdef MAP_ANONYMOUS
-	PyDict_SetItemString(dict, "MAP_ANON", PyInt_FromLong(MAP_ANONYMOUS) );
-	PyDict_SetItemString(dict, "MAP_ANONYMOUS",
-			     PyInt_FromLong(MAP_ANONYMOUS) );
+	setint(dict, "MAP_ANON", MAP_ANONYMOUS);
+	setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS);
 #endif
 
-	PyDict_SetItemString(dict, "PAGESIZE",
-			     PyInt_FromLong((long)my_getpagesize()));
-
-	PyDict_SetItemString(dict, "ACCESS_READ",
-			     PyInt_FromLong(ACCESS_READ));
-	PyDict_SetItemString(dict, "ACCESS_WRITE",
-			     PyInt_FromLong(ACCESS_WRITE));
-	PyDict_SetItemString(dict, "ACCESS_COPY",
-			     PyInt_FromLong(ACCESS_COPY));
+	setint(dict, "PAGESIZE", (long)my_getpagesize());
+
+	setint(dict, "ACCESS_READ", ACCESS_READ);
+	setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
+	setint(dict, "ACCESS_COPY", ACCESS_COPY);
 }

Modified: stackless/trunk/Modules/operator.c
==============================================================================
--- stackless/trunk/Modules/operator.c	(original)
+++ stackless/trunk/Modules/operator.c	Mon Aug 21 11:10:05 2006
@@ -139,15 +139,7 @@
 static PyObject *
 op_index(PyObject *s, PyObject *a)
 {
-	Py_ssize_t i;
-	PyObject *a1;
-	if (!PyArg_UnpackTuple(a,"index", 1, 1, &a1))
-		return NULL;		
-	i = PyNumber_Index(a1);
-	if (i == -1 && PyErr_Occurred())
-		return NULL;
-	else
-		return PyInt_FromSsize_t(i);
+	return PyNumber_Index(a);
 }
 
 static PyObject*
@@ -249,7 +241,7 @@
 
 spam1(is_, "is_(a, b) -- Same as a is b.")
 spam1(is_not, "is_not(a, b) -- Same as a is not b.")
-spam2(index, __index__, "index(a) -- Same as a.__index__()")
+spam2o(index, __index__, "index(a) -- Same as a.__index__()")
 spam2(add,__add__, "add(a, b) -- Same as a + b.")
 spam2(sub,__sub__, "sub(a, b) -- Same as a - b.")
 spam2(mul,__mul__, "mul(a, b) -- Same as a * b.")

Modified: stackless/trunk/Modules/posixmodule.c
==============================================================================
--- stackless/trunk/Modules/posixmodule.c	(original)
+++ stackless/trunk/Modules/posixmodule.c	Mon Aug 21 11:10:05 2006
@@ -1121,6 +1121,8 @@
 #else
 	ival = PyInt_FromLong((long)sec);
 #endif
+	if (!ival)
+		return;
 	if (_stat_float_times) {
 		fval = PyFloat_FromDouble(sec + 1e-9*nsec);
 	} else {

Modified: stackless/trunk/Modules/rgbimgmodule.c
==============================================================================
--- stackless/trunk/Modules/rgbimgmodule.c	(original)
+++ stackless/trunk/Modules/rgbimgmodule.c	Mon Aug 21 11:10:05 2006
@@ -410,6 +410,11 @@
 		addlongimgtag(base, xsize, ysize);
 #endif
 		verdat = (unsigned char *)malloc(xsize);
+		if (!verdat) {
+			Py_CLEAR(rv);
+			goto finally;
+		}
+
 		fseek(inf, 512, SEEK_SET);
 		for (z = 0; z < zsize; z++) {
 			lptr = base;
@@ -431,10 +436,14 @@
 			copybw((Py_Int32 *) base, xsize * ysize);
 	}
   finally:
-	free(starttab);
-	free(lengthtab);
-	free(rledat);
-	free(verdat);
+	if (starttab)
+		free(starttab);
+	if (lengthtab)
+		free(lengthtab);
+	if (rledat)
+		free(rledat);
+	if (verdat)
+		free(verdat);
 	fclose(inf);
 	return rv;
 }

Modified: stackless/trunk/Modules/socketmodule.c
==============================================================================
--- stackless/trunk/Modules/socketmodule.c	(original)
+++ stackless/trunk/Modules/socketmodule.c	Mon Aug 21 11:10:05 2006
@@ -3041,17 +3041,20 @@
 	if ((addr_list = PyList_New(0)) == NULL)
 		goto err;
 
-	for (pch = h->h_aliases; *pch != NULL; pch++) {
-		int status;
-		tmp = PyString_FromString(*pch);
-		if (tmp == NULL)
-			goto err;
+	/* SF #1511317: h_aliases can be NULL */
+	if (h->h_aliases) {
+		for (pch = h->h_aliases; *pch != NULL; pch++) {
+			int status;
+			tmp = PyString_FromString(*pch);
+			if (tmp == NULL)
+				goto err;
 
-		status = PyList_Append(name_list, tmp);
-		Py_DECREF(tmp);
+			status = PyList_Append(name_list, tmp);
+			Py_DECREF(tmp);
 
-		if (status)
-			goto err;
+			if (status)
+				goto err;
+		}
 	}
 
 	for (pch = h->h_addr_list; *pch != NULL; pch++) {

Modified: stackless/trunk/Modules/unicodedata.c
==============================================================================
--- stackless/trunk/Modules/unicodedata.c	(original)
+++ stackless/trunk/Modules/unicodedata.c	Mon Aug 21 11:10:05 2006
@@ -1,8 +1,8 @@
 /* ------------------------------------------------------------------------
 
-   unicodedata -- Provides access to the Unicode 3.2 data base.
+   unicodedata -- Provides access to the Unicode 4.1 data base.
 
-   Data was extracted from the Unicode 3.2 UnicodeData.txt file.
+   Data was extracted from the Unicode 4.1 UnicodeData.txt file.
 
    Written by Marc-Andre Lemburg (mal at lemburg.com).
    Modified for Python 2.0 by Fredrik Lundh (fredrik at pythonware.com)
@@ -1078,6 +1078,7 @@
 {
     Py_UCS4 code;
     Py_UNICODE str[1];
+    char errbuf[256];
 
     char* name;
     int namelen;
@@ -1085,11 +1086,19 @@
         return NULL;
 
     if (!_getcode(self, name, namelen, &code)) {
+	/* XXX(nnorwitz): why are we allocating for the error msg?
+		Why not always use snprintf? */
         char fmt[] = "undefined character name '%s'";
         char *buf = PyMem_MALLOC(sizeof(fmt) + namelen);
-        sprintf(buf, fmt, name);
+        if (buf)
+            sprintf(buf, fmt, name);
+        else {
+            buf = errbuf;
+            PyOS_snprintf(buf, sizeof(errbuf), fmt, name);
+        }
         PyErr_SetString(PyExc_KeyError, buf);
-        PyMem_FREE(buf);
+        if (buf != errbuf)
+        	PyMem_FREE(buf);
         return NULL;
     }
 
@@ -1173,11 +1182,11 @@
 "This module provides access to the Unicode Character Database which\n\
 defines character properties for all Unicode characters. The data in\n\
 this database is based on the UnicodeData.txt file version\n\
-3.2.0 which is publically available from ftp://ftp.unicode.org/.\n\
+4.1.0 which is publically available from ftp://ftp.unicode.org/.\n\
 \n\
 The module uses the same names and symbols as defined by the\n\
-UnicodeData File Format 3.2.0 (see\n\
-http://www.unicode.org/Public/3.2-Update/UnicodeData-3.2.0.html).");
+UnicodeData File Format 4.1.0 (see\n\
+http://www.unicode.org/Public/4.1.0/ucd/UCD.html).");
 
 PyMODINIT_FUNC
 initunicodedata(void)

Modified: stackless/trunk/Modules/zipimport.c
==============================================================================
--- stackless/trunk/Modules/zipimport.c	(original)
+++ stackless/trunk/Modules/zipimport.c	Mon Aug 21 11:10:05 2006
@@ -950,6 +950,9 @@
 	char *buf, *q, *p = PyString_AsString(source);
 	PyObject *fixed_source;
 
+	if (!p)
+		return NULL;
+
 	/* one char extra for trailing \n and one for terminating \0 */
 	buf = (char *)PyMem_Malloc(PyString_Size(source) + 2);
 	if (buf == NULL) {

Modified: stackless/trunk/Objects/abstract.c
==============================================================================
--- stackless/trunk/Objects/abstract.c	(original)
+++ stackless/trunk/Objects/abstract.c	Mon Aug 21 11:10:05 2006
@@ -9,8 +9,6 @@
 #define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
 				Py_TPFLAGS_CHECKTYPES)
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
-
 
 /* Shorthands to return certain errors */
 
@@ -123,9 +121,9 @@
 		return m->mp_subscript(o, key);
 
 	if (o->ob_type->tp_as_sequence) {
-		PyNumberMethods *nb = key->ob_type->tp_as_number;
-		if (nb != NULL && HASINDEX(key) && nb->nb_index != NULL) {
-			Py_ssize_t key_value = nb->nb_index(key);
+		if (PyIndex_Check(key)) {
+			Py_ssize_t key_value;
+			key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
 			if (key_value == -1 && PyErr_Occurred())
 				return NULL;
 			return PySequence_GetItem(o, key_value);
@@ -152,9 +150,9 @@
 		return m->mp_ass_subscript(o, key, value);
 
 	if (o->ob_type->tp_as_sequence) {
-		PyNumberMethods *nb = key->ob_type->tp_as_number;
-		if (nb != NULL && HASINDEX(key) && nb->nb_index != NULL) {
-			Py_ssize_t key_value = nb->nb_index(key);
+		if (PyIndex_Check(key)) {
+			Py_ssize_t key_value;
+			key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
 			if (key_value == -1 && PyErr_Occurred())
 				return -1;
 			return PySequence_SetItem(o, key_value, value);
@@ -184,9 +182,9 @@
 		return m->mp_ass_subscript(o, key, (PyObject*)NULL);
 
 	if (o->ob_type->tp_as_sequence) {
-		PyNumberMethods *nb = key->ob_type->tp_as_number;
-		if (nb != NULL && HASINDEX(key) && nb->nb_index != NULL) {
-			Py_ssize_t key_value = nb->nb_index(key);
+		if (PyIndex_Check(key)) {
+			Py_ssize_t key_value;
+			key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
 			if (key_value == -1 && PyErr_Occurred())
 				return -1;
 			return PySequence_DelItem(o, key_value);
@@ -654,9 +652,8 @@
 sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
 {
 	Py_ssize_t count;
-	PyNumberMethods *nb = n->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(n) && nb->nb_index != NULL) {
-		count = nb->nb_index(n);
+	if (PyIndex_Check(n)) {
+		count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
 		if (count == -1 && PyErr_Occurred())
 			return NULL;
 	}
@@ -939,23 +936,87 @@
 	return x;
 }
 
-/* Return a Py_ssize_t integer from the object item */
-Py_ssize_t
+/* Return a Python Int or Long from the object item 
+   Raise TypeError if the result is not an int-or-long
+   or if the object cannot be interpreted as an index. 
+*/
+PyObject *
 PyNumber_Index(PyObject *item)
 {
-	Py_ssize_t value = -1;
-	PyNumberMethods *nb = item->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		value = nb->nb_index(item);
+	PyObject *result = NULL;
+	if (item == NULL)
+		return null_error();
+	if (PyInt_Check(item) || PyLong_Check(item)) {
+		Py_INCREF(item);
+		return item;
+	}
+	if (PyIndex_Check(item)) {
+		result = item->ob_type->tp_as_number->nb_index(item);
+		if (result &&
+		    !PyInt_Check(result) && !PyLong_Check(result)) {
+			PyErr_Format(PyExc_TypeError,
+				     "__index__ returned non-(int,long) " \
+				     "(type %.200s)",
+				     result->ob_type->tp_name);
+			Py_DECREF(result);
+			return NULL;
+		}
 	}
 	else {
 		PyErr_Format(PyExc_TypeError,
 			     "'%.200s' object cannot be interpreted "
 			     "as an index", item->ob_type->tp_name);
 	}
-	return value;
+	return result;
+}
+
+/* Return an error on Overflow only if err is not NULL*/
+
+Py_ssize_t
+PyNumber_AsSsize_t(PyObject *item, PyObject *err)
+{
+	Py_ssize_t result;
+	PyObject *runerr;
+	PyObject *value = PyNumber_Index(item);
+	if (value == NULL)
+		return -1;
+
+	/* We're done if PyInt_AsSsize_t() returns without error. */
+	result = PyInt_AsSsize_t(value);
+	if (result != -1 || !(runerr = PyErr_Occurred()))
+		goto finish;
+
+	/* Error handling code -- only manage OverflowError differently */
+	if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError)) 
+		goto finish;
+
+	PyErr_Clear();
+	/* If no error-handling desired then the default clipping 
+	   is sufficient.
+	 */
+	if (!err) {
+		assert(PyLong_Check(value));
+		/* Whether or not it is less than or equal to 
+		   zero is determined by the sign of ob_size
+		*/
+		if (_PyLong_Sign(value) < 0) 
+			result = PY_SSIZE_T_MIN;
+		else
+			result = PY_SSIZE_T_MAX;
+	}
+	else {
+		/* Otherwise replace the error with caller's error object. */
+		PyErr_Format(err,
+			     "cannot fit '%.200s' into an index-sized integer", 
+			     item->ob_type->tp_name); 
+	}
+	
+ finish:
+	Py_DECREF(value);
+	return result;
 }
 
+
 PyObject *
 PyNumber_Int(PyObject *o)
 {
@@ -1115,7 +1176,7 @@
 	if (m && m->sq_length)
 		return m->sq_length(s);
 
-	type_error("non-sequence object of type '%.200s' has no len()", s);
+	type_error("object of type '%.200s' has no len()", s);
 	return -1;
 }
 
@@ -1706,7 +1767,7 @@
 	if (m && m->mp_length)
 		return m->mp_length(o);
 
-	type_error("non-mapping object of type '%.200s' has no len()", o);
+	type_error("object of type '%.200s' has no len()", o);
 	return -1;
 }
 

Modified: stackless/trunk/Objects/bufferobject.c
==============================================================================
--- stackless/trunk/Objects/bufferobject.c	(original)
+++ stackless/trunk/Objects/bufferobject.c	Mon Aug 21 11:10:05 2006
@@ -272,7 +272,7 @@
 	if (min_len > 0) {
 		cmp = memcmp(p1, p2, min_len);
 		if (cmp != 0)
-			return cmp;
+			return cmp < 0 ? -1 : 1;
 	}
 	return (len_self < len_other) ? -1 : (len_self > len_other) ? 1 : 0;
 }

Modified: stackless/trunk/Objects/classobject.c
==============================================================================
--- stackless/trunk/Objects/classobject.c	(original)
+++ stackless/trunk/Objects/classobject.c	Mon Aug 21 11:10:05 2006
@@ -104,8 +104,14 @@
 	op->cl_name = name;
 	if (getattrstr == NULL) {
 		getattrstr = PyString_InternFromString("__getattr__");
+		if (getattrstr == NULL)
+			return NULL;
 		setattrstr = PyString_InternFromString("__setattr__");
+		if (setattrstr == NULL)
+			return NULL;
 		delattrstr = PyString_InternFromString("__delattr__");
+		if (delattrstr == NULL)
+			return NULL;
 	}
 	op->cl_getattr = class_lookup(op, getattrstr, &dummy);
 	op->cl_setattr = class_lookup(op, setattrstr, &dummy);
@@ -523,11 +529,14 @@
 	PyObject *init;
 	static PyObject *initstr;
 
+	if (initstr == NULL) {
+		initstr = PyString_InternFromString("__init__");
+		if (initstr == NULL)
+			return NULL;
+	}
 	inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
 	if (inst == NULL)
 		return NULL;
-	if (initstr == NULL)
-		initstr = PyString_InternFromString("__init__");
 	init = instance_getattr2(inst, initstr);
 	if (init == NULL) {
 		if (PyErr_Occurred()) {
@@ -613,9 +622,12 @@
 	/* Save the current exception, if any. */
 	PyErr_Fetch(&error_type, &error_value, &error_traceback);
 	/* Execute __del__ method, if any. */
-	if (delstr == NULL)
+	if (delstr == NULL) {
 		delstr = PyString_InternFromString("__del__");
-	if ((del = instance_getattr2(inst, delstr)) != NULL) {
+		if (delstr == NULL)
+			PyErr_WriteUnraisable((PyObject*)inst);
+	}
+	if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
 		PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
 		if (res == NULL)
 			PyErr_WriteUnraisable(del);
@@ -841,8 +853,11 @@
 	PyObject *res;
 	static PyObject *reprstr;
 
-	if (reprstr == NULL)
+	if (reprstr == NULL) {
 		reprstr = PyString_InternFromString("__repr__");
+		if (reprstr == NULL)
+			return NULL;
+	}
 	func = instance_getattr(inst, reprstr);
 	if (func == NULL) {
 		PyObject *classname, *mod;
@@ -877,8 +892,11 @@
 	PyObject *res;
 	static PyObject *strstr;
 
-	if (strstr == NULL)
+	if (strstr == NULL) {
 		strstr = PyString_InternFromString("__str__");
+		if (strstr == NULL)
+			return NULL;
+	}
 	func = instance_getattr(inst, strstr);
 	if (func == NULL) {
 		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
@@ -899,8 +917,11 @@
 	long outcome;
 	static PyObject *hashstr, *eqstr, *cmpstr;
 
-	if (hashstr == NULL)
+	if (hashstr == NULL) {
 		hashstr = PyString_InternFromString("__hash__");
+		if (hashstr == NULL)
+			return -1;
+	}
 	func = instance_getattr(inst, hashstr);
 	if (func == NULL) {
 		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
@@ -909,15 +930,21 @@
 		/* If there is no __eq__ and no __cmp__ method, we hash on the
 		   address.  If an __eq__ or __cmp__ method exists, there must
 		   be a __hash__. */
-		if (eqstr == NULL)
+		if (eqstr == NULL) {
 			eqstr = PyString_InternFromString("__eq__");
+			if (eqstr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, eqstr);
 		if (func == NULL) {
 			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 				return -1;
 			PyErr_Clear();
-			if (cmpstr == NULL)
+			if (cmpstr == NULL) {
 				cmpstr = PyString_InternFromString("__cmp__");
+				if (cmpstr == NULL)
+					return -1;
+			}
 			func = instance_getattr(inst, cmpstr);
 			if (func == NULL) {
 				if (!PyErr_ExceptionMatches(
@@ -935,11 +962,9 @@
 	Py_DECREF(func);
 	if (res == NULL)
 		return -1;
-	if (PyInt_Check(res)) {
-		outcome = PyInt_AsLong(res);
-		if (outcome == -1)
-			outcome = -2;
-	}
+	if (PyInt_Check(res) || PyLong_Check(res))
+		/* This already converts a -1 result to -2. */
+		outcome = res->ob_type->tp_hash(res);
 	else {
 		PyErr_SetString(PyExc_TypeError,
 				"__hash__() should return an int");
@@ -967,8 +992,11 @@
 	PyObject *res;
 	Py_ssize_t outcome;
 
-	if (lenstr == NULL)
+	if (lenstr == NULL) {
 		lenstr = PyString_InternFromString("__len__");
+		if (lenstr == NULL)
+			return -1;
+	}
 	func = instance_getattr(inst, lenstr);
 	if (func == NULL)
 		return -1;
@@ -977,24 +1005,25 @@
 	if (res == NULL)
 		return -1;
 	if (PyInt_Check(res)) {
-		Py_ssize_t temp = PyInt_AsSsize_t(res);
-		if (temp == -1 && PyErr_Occurred()) {
+		outcome = PyInt_AsSsize_t(res);
+		if (outcome == -1 && PyErr_Occurred()) {
 			Py_DECREF(res);
 			return -1;
 		}
-		outcome = (Py_ssize_t)temp;
-#if SIZEOF_SIZE_T < SIZEOF_LONG
+#if SIZEOF_SIZE_T < SIZEOF_INT
 		/* Overflow check -- range of PyInt is more than C int */
-		if (outcome != temp) {
+		if (outcome != (int)outcome) {
 			PyErr_SetString(PyExc_OverflowError,
 			 "__len__() should return 0 <= outcome < 2**31");
 			outcome = -1;
 		}
 		else
 #endif
-		if (outcome < 0)
+		if (outcome < 0) {
 			PyErr_SetString(PyExc_ValueError,
 					"__len__() should return >= 0");
+			outcome = -1;
+		}
 	}
 	else {
 		PyErr_SetString(PyExc_TypeError,
@@ -1012,8 +1041,11 @@
 	PyObject *arg;
 	PyObject *res;
 
-	if (getitemstr == NULL)
+	if (getitemstr == NULL) {
 		getitemstr = PyString_InternFromString("__getitem__");
+		if (getitemstr == NULL)
+			return NULL;
+	}
 	func = instance_getattr(inst, getitemstr);
 	if (func == NULL)
 		return NULL;
@@ -1036,13 +1068,19 @@
 	PyObject *res;
 
 	if (value == NULL) {
-		if (delitemstr == NULL)
+		if (delitemstr == NULL) {
 			delitemstr = PyString_InternFromString("__delitem__");
+			if (delitemstr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, delitemstr);
 	}
 	else {
-		if (setitemstr == NULL)
+		if (setitemstr == NULL) {
 			setitemstr = PyString_InternFromString("__setitem__");
+			if (setitemstr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, setitemstr);
 	}
 	if (func == NULL)
@@ -1075,8 +1113,11 @@
 {
 	PyObject *func, *res;
 
-	if (getitemstr == NULL)
+	if (getitemstr == NULL) {
 		getitemstr = PyString_InternFromString("__getitem__");
+		if (getitemstr == NULL)
+			return NULL;
+	}
 	func = instance_getattr(inst, getitemstr);
 	if (func == NULL)
 		return NULL;
@@ -1091,8 +1132,11 @@
 	PyObject *func, *arg, *res;
 	static PyObject *getslicestr;
 
-	if (getslicestr == NULL)
+	if (getslicestr == NULL) {
 		getslicestr = PyString_InternFromString("__getslice__");
+		if (getslicestr == NULL)
+			return NULL;
+	}
 	func = instance_getattr(inst, getslicestr);
 
 	if (func == NULL) {
@@ -1100,8 +1144,11 @@
 			return NULL;
 		PyErr_Clear();
 
-		if (getitemstr == NULL)
+		if (getitemstr == NULL) {
 			getitemstr = PyString_InternFromString("__getitem__");
+			if (getitemstr == NULL)
+				return NULL;
+		}
 		func = instance_getattr(inst, getitemstr);
 		if (func == NULL)
 			return NULL;
@@ -1125,13 +1172,19 @@
 	PyObject *func, *arg, *res;
 
 	if (item == NULL) {
-		if (delitemstr == NULL)
+		if (delitemstr == NULL) {
 			delitemstr = PyString_InternFromString("__delitem__");
+			if (delitemstr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, delitemstr);
 	}
 	else {
-		if (setitemstr == NULL)
+		if (setitemstr == NULL) {
 			setitemstr = PyString_InternFromString("__setitem__");
+			if (setitemstr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, setitemstr);
 	}
 	if (func == NULL)
@@ -1160,17 +1213,23 @@
 	static PyObject *setslicestr, *delslicestr;
 
 	if (value == NULL) {
-		if (delslicestr == NULL)
+		if (delslicestr == NULL) {
 			delslicestr =
 				PyString_InternFromString("__delslice__");
+			if (delslicestr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, delslicestr);
 		if (func == NULL) {
 			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 				return -1;
 			PyErr_Clear();
-			if (delitemstr == NULL)
+			if (delitemstr == NULL) {
 				delitemstr =
 				    PyString_InternFromString("__delitem__");
+				if (delitemstr == NULL)
+					return -1;
+			}
 			func = instance_getattr(inst, delitemstr);
 			if (func == NULL)
 				return -1;
@@ -1181,17 +1240,23 @@
 			arg = Py_BuildValue("(nn)", i, j);
 	}
 	else {
-		if (setslicestr == NULL)
+		if (setslicestr == NULL) {
 			setslicestr =
 				PyString_InternFromString("__setslice__");
+			if (setslicestr == NULL)
+				return -1;
+		}
 		func = instance_getattr(inst, setslicestr);
 		if (func == NULL) {
 			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 				return -1;
 			PyErr_Clear();
-			if (setitemstr == NULL)
+			if (setitemstr == NULL) {
 				setitemstr =
 				    PyString_InternFromString("__setitem__");
+				if (setitemstr == NULL)
+					return -1;
+			}
 			func = instance_getattr(inst, setitemstr);
 			if (func == NULL)
 				return -1;
@@ -1464,7 +1529,8 @@
 #define UNARY(funcname, methodname) \
 static PyObject *funcname(PyInstanceObject *self) { \
 	static PyObject *o; \
-	if (o == NULL) o = PyString_InternFromString(methodname); \
+	if (o == NULL) { o = PyString_InternFromString(methodname); \
+			 if (o == NULL) return NULL; } \
 	return generic_unary_op(self, o); \
 }
 
@@ -1636,14 +1702,20 @@
 	long outcome;
 	static PyObject *nonzerostr;
 
-	if (nonzerostr == NULL)
+	if (nonzerostr == NULL) {
 		nonzerostr = PyString_InternFromString("__nonzero__");
+		if (nonzerostr == NULL)
+			return -1;
+	}
 	if ((func = instance_getattr(self, nonzerostr)) == NULL) {
 		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 			return -1;
 		PyErr_Clear();
-		if (lenstr == NULL)
+		if (lenstr == NULL) {
 			lenstr = PyString_InternFromString("__len__");
+			if (lenstr == NULL)
+				return -1;
+		}
 		if ((func = instance_getattr(self, lenstr)) == NULL) {
 			if (!PyErr_ExceptionMatches(PyExc_AttributeError))
 				return -1;
@@ -1673,40 +1745,28 @@
 	return outcome > 0;
 }
 
-static Py_ssize_t
+static PyObject *
 instance_index(PyInstanceObject *self)
 {
 	PyObject *func, *res;
-	Py_ssize_t outcome;
 	static PyObject *indexstr = NULL;
 
 	if (indexstr == NULL) {
 		indexstr = PyString_InternFromString("__index__");
 		if (indexstr == NULL)
-			return -1;
+			return NULL;
 	}	
 	if ((func = instance_getattr(self, indexstr)) == NULL) {
 		if (!PyErr_ExceptionMatches(PyExc_AttributeError))
-			return -1;
+			return NULL;
 		PyErr_Clear();
 		PyErr_SetString(PyExc_TypeError, 
 				"object cannot be interpreted as an index");
-		return -1;
+		return NULL;
 	}
 	res = PyEval_CallObject(func, (PyObject *)NULL);
 	Py_DECREF(func);
-	if (res == NULL)
-		return -1;
-	if (PyInt_Check(res) || PyLong_Check(res)) {
-		outcome = res->ob_type->tp_as_number->nb_index(res);
-	}
-	else {
-		PyErr_SetString(PyExc_TypeError, 
-				"__index__ must return an int or a long");
-		outcome = -1;
-	}
-	Py_DECREF(res);
-	return outcome;
+	return res;
 }
 
 
@@ -1937,8 +1997,11 @@
 {
 	PyObject *func;
 
-	if (nextstr == NULL)
+	if (nextstr == NULL) {
 		nextstr = PyString_InternFromString("next");
+		if (nextstr == NULL)
+			return NULL;
+	}
 
 	if ((func = instance_getattr(self, nextstr)) != NULL) {
 		PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
@@ -2032,7 +2095,7 @@
 	instance_truediv,		/* nb_true_divide */
 	instance_ifloordiv,		/* nb_inplace_floor_divide */
 	instance_itruediv,		/* nb_inplace_true_divide */
-	(lenfunc)instance_index,	/* nb_index */
+	(unaryfunc)instance_index,	/* nb_index */
 };
 
 PyTypeObject PyInstance_Type = {

Modified: stackless/trunk/Objects/descrobject.c
==============================================================================
--- stackless/trunk/Objects/descrobject.c	(original)
+++ stackless/trunk/Objects/descrobject.c	Mon Aug 21 11:10:05 2006
@@ -1218,7 +1218,6 @@
 property_init(PyObject *self, PyObject *args, PyObject *kwds)
 {
 	PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL;
-	PyObject *get_doc = NULL;
 	static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0};
 	propertyobject *gs = (propertyobject *)self;
 
@@ -1233,20 +1232,22 @@
 	if (del == Py_None)
 		del = NULL;
 
-	/* if no docstring given and the getter has one, use that one */
-	if ((doc == NULL || doc == Py_None) && get != NULL &&
-	    PyObject_HasAttrString(get, "__doc__")) {
-		if (!(get_doc = PyObject_GetAttrString(get, "__doc__")))
-			return -1;
-		Py_DECREF(get_doc); /* it is INCREF'd again below */
-		doc = get_doc;
-	}
-
 	Py_XINCREF(get);
 	Py_XINCREF(set);
 	Py_XINCREF(del);
 	Py_XINCREF(doc);
 
+	/* if no docstring given and the getter has one, use that one */
+	if ((doc == NULL || doc == Py_None) && get != NULL) {
+		PyObject *get_doc = PyObject_GetAttrString(get, "__doc__");
+		if (get_doc != NULL) {
+			Py_XDECREF(doc);
+			doc = get_doc;  /* get_doc already INCREF'd by GetAttr */
+		} else {
+			PyErr_Clear();
+		}
+	}
+
 	gs->prop_get = get;
 	gs->prop_set = set;
 	gs->prop_del = del;

Modified: stackless/trunk/Objects/dictnotes.txt
==============================================================================
--- stackless/trunk/Objects/dictnotes.txt	(original)
+++ stackless/trunk/Objects/dictnotes.txt	Mon Aug 21 11:10:05 2006
@@ -243,7 +243,7 @@
 Caching Lookups
 ---------------
 The idea is to exploit key access patterns by anticipating future lookups
-based of previous lookups.
+based on previous lookups.
 
 The simplest incarnation is to save the most recently accessed entry.
 This gives optimal performance for use cases where every get is followed

Modified: stackless/trunk/Objects/dictobject.c
==============================================================================
--- stackless/trunk/Objects/dictobject.c	(original)
+++ stackless/trunk/Objects/dictobject.c	Mon Aug 21 11:10:05 2006
@@ -532,7 +532,7 @@
 /* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
  * that may occur (originally dicts supported only string keys, and exceptions
  * weren't possible).  So, while the original intent was that a NULL return
- * meant the key wasn't present, it reality it can mean that, or that an error
+ * meant the key wasn't present, in reality it can mean that, or that an error
  * (suppressed) occurred while computing the key's hash, or that some error
  * (suppressed) occurred when comparing keys in the dict's internal probe
  * sequence.  A nasty example of the latter is when a Python-coded comparison

Modified: stackless/trunk/Objects/exceptions.c
==============================================================================
--- stackless/trunk/Objects/exceptions.c	(original)
+++ stackless/trunk/Objects/exceptions.c	Mon Aug 21 11:10:05 2006
@@ -1956,6 +1956,14 @@
           "Base class for warnings about probable mistakes in module imports");
 
 
+/*
+ *    UnicodeWarning extends Warning
+ */
+SimpleExtendsException(PyExc_Warning, UnicodeWarning,
+    "Base class for warnings about Unicode related problems, mostly\n"
+    "related to conversion problems.");
+
+
 /* Pre-computed MemoryError instance.  Best to create this as early as
  * possible and not wait until a MemoryError is actually raised!
  */
@@ -2059,6 +2067,7 @@
     PRE_INIT(RuntimeWarning)
     PRE_INIT(FutureWarning)
     PRE_INIT(ImportWarning)
+    PRE_INIT(UnicodeWarning)
 
     m = Py_InitModule4("exceptions", functions, exceptions_doc,
         (PyObject *)NULL, PYTHON_API_VERSION);
@@ -2127,6 +2136,7 @@
     POST_INIT(RuntimeWarning)
     POST_INIT(FutureWarning)
     POST_INIT(ImportWarning)
+    POST_INIT(UnicodeWarning)
 
     PyExc_MemoryErrorInst = BaseException_new(&_PyExc_MemoryError, NULL, NULL);
     if (!PyExc_MemoryErrorInst)

Modified: stackless/trunk/Objects/intobject.c
==============================================================================
--- stackless/trunk/Objects/intobject.c	(original)
+++ stackless/trunk/Objects/intobject.c	Mon Aug 21 11:10:05 2006
@@ -193,16 +193,21 @@
 	PyIntObject *io;
 	Py_ssize_t val;
 #endif
-	if (op && !PyInt_CheckExact(op) && PyLong_Check(op))
+
+	if (op == NULL) {
+		PyErr_SetString(PyExc_TypeError, "an integer is required");
+		return -1;
+	}
+
+	if (PyInt_Check(op))
+		return PyInt_AS_LONG((PyIntObject*) op);
+	if (PyLong_Check(op))
 		return _PyLong_AsSsize_t(op);
 #if SIZEOF_SIZE_T == SIZEOF_LONG
 	return PyInt_AsLong(op);
 #else
 
-	if (op && PyInt_Check(op))
-		return PyInt_AS_LONG((PyIntObject*) op);
-
-	if (op == NULL || (nb = op->ob_type->tp_as_number) == NULL ||
+	if ((nb = op->ob_type->tp_as_number) == NULL ||
 	    (nb->nb_int == NULL && nb->nb_long == 0)) {
 		PyErr_SetString(PyExc_TypeError, "an integer is required");
 		return -1;
@@ -1079,7 +1084,7 @@
 	int_true_divide,	/* nb_true_divide */
 	0,			/* nb_inplace_floor_divide */
 	0,			/* nb_inplace_true_divide */
-	PyInt_AsSsize_t,	/* nb_index */
+	(unaryfunc)int_int,	/* nb_index */
 };
 
 PyTypeObject PyInt_Type = {

Modified: stackless/trunk/Objects/listobject.c
==============================================================================
--- stackless/trunk/Objects/listobject.c	(original)
+++ stackless/trunk/Objects/listobject.c	Mon Aug 21 11:10:05 2006
@@ -2450,14 +2450,13 @@
 "list() -> new list\n"
 "list(sequence) -> new list initialized from sequence's items");
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
 
 static PyObject *
 list_subscript(PyListObject* self, PyObject* item)
 {
-	PyNumberMethods *nb = item->ob_type->tp_as_number;	
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(item);
+	if (PyIndex_Check(item)) {
+		Py_ssize_t i;
+		i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 		if (i == -1 && PyErr_Occurred())
 			return NULL;
 		if (i < 0)
@@ -2504,9 +2503,8 @@
 static int
 list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
 {
-	PyNumberMethods *nb = item->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(item);
+	if (PyIndex_Check(item)) {
+		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 		if (i == -1 && PyErr_Occurred())
 			return -1;
 		if (i < 0)
@@ -2541,6 +2539,10 @@
 
 			garbage = (PyObject**)
 				PyMem_MALLOC(slicelength*sizeof(PyObject*));
+			if (!garbage) {
+				PyErr_NoMemory();
+				return -1;
+			}
 
 			/* drawing pictures might help
 			   understand these for loops */
@@ -2589,9 +2591,9 @@
 			else {
 				seq = PySequence_Fast(value,
 					"must assign iterable to extended slice");
-				if (!seq)
-					return -1;
 			}
+			if (!seq)
+				return -1;
 
 			if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
 				PyErr_Format(PyExc_ValueError,

Modified: stackless/trunk/Objects/longobject.c
==============================================================================
--- stackless/trunk/Objects/longobject.c	(original)
+++ stackless/trunk/Objects/longobject.c	Mon Aug 21 11:10:05 2006
@@ -240,8 +240,11 @@
 	return -1;
 }
 
-static Py_ssize_t
-_long_as_ssize_t(PyObject *vv) {
+/* Get a Py_ssize_t from a long int object.
+   Returns -1 and sets an error condition if overflow occurs. */
+
+Py_ssize_t
+_PyLong_AsSsize_t(PyObject *vv) {
 	register PyLongObject *v;
 	size_t x, prev;
 	Py_ssize_t i;
@@ -277,45 +280,7 @@
  overflow:
 	PyErr_SetString(PyExc_OverflowError,
 			"long int too large to convert to int");
-	if (sign > 0)
-		return PY_SSIZE_T_MAX;
-	else
-		return PY_SSIZE_T_MIN;
-}
-
-/* Get a Py_ssize_t from a long int object.
-   Returns -1 and sets an error condition if overflow occurs. */
-
-Py_ssize_t
-_PyLong_AsSsize_t(PyObject *vv)
-{
-	Py_ssize_t x;
-
-	x = _long_as_ssize_t(vv);
-	if (PyErr_Occurred()) return -1;
-	return x;
-}
-
-
-/* Get a Py_ssize_t from a long int object.
-   Silently reduce values larger than PY_SSIZE_T_MAX to PY_SSIZE_T_MAX,
-   and silently boost values less than -PY_SSIZE_T_MAX-1 to -PY_SSIZE_T_MAX-1.
-   On error, return -1 with an exception set.
-*/
-
-static Py_ssize_t
-long_index(PyObject *vv)
-{
-	Py_ssize_t x;
-
-	x = _long_as_ssize_t(vv);
-	if (PyErr_Occurred()) {
-		/* If overflow error, ignore the error */
-		if (x != -1) {
-			PyErr_Clear();
-		}
-	}
-	return x;
+	return -1;
 }
 
 /* Get a C unsigned long int from a long int object.
@@ -3405,7 +3370,7 @@
 	long_true_divide,		/* nb_true_divide */
 	0,				/* nb_inplace_floor_divide */
 	0,				/* nb_inplace_true_divide */
-	long_index,			/* nb_index */
+	long_long,			/* nb_index */
 };
 
 PyTypeObject PyLong_Type = {

Modified: stackless/trunk/Objects/object.c
==============================================================================
--- stackless/trunk/Objects/object.c	(original)
+++ stackless/trunk/Objects/object.c	Mon Aug 21 11:10:05 2006
@@ -731,23 +731,6 @@
 		return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
 	}
 
-#ifdef Py_USING_UNICODE
-	/* Special case for Unicode */
-	if (PyUnicode_Check(v) || PyUnicode_Check(w)) {
-		c = PyUnicode_Compare(v, w);
-		if (!PyErr_Occurred())
-			return c;
-		/* TypeErrors are ignored: if Unicode coercion fails due
-		   to one of the arguments not having the right type, we
-		   continue as defined by the coercion protocol (see
-		   above).  Luckily, decoding errors are reported as
-		   ValueErrors and are not masked by this technique. */
-		if (!PyErr_ExceptionMatches(PyExc_TypeError))
-			return -2;
-		PyErr_Clear();
-	}
-#endif
-
 	/* None is smaller than anything */
 	if (v == Py_None)
 		return -1;

Modified: stackless/trunk/Objects/sliceobject.c
==============================================================================
--- stackless/trunk/Objects/sliceobject.c	(original)
+++ stackless/trunk/Objects/sliceobject.c	Mon Aug 21 11:10:05 2006
@@ -252,7 +252,7 @@
 {
 	Py_ssize_t ilen, start, stop, step, slicelength;
 
-	ilen = PyInt_AsSsize_t(len);
+	ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError);
 
 	if (ilen == -1 && PyErr_Occurred()) {
 		return NULL;

Modified: stackless/trunk/Objects/stringobject.c
==============================================================================
--- stackless/trunk/Objects/stringobject.c	(original)
+++ stackless/trunk/Objects/stringobject.c	Mon Aug 21 11:10:05 2006
@@ -1184,14 +1184,11 @@
 	return x;
 }
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
-
 static PyObject*
 string_subscript(PyStringObject* self, PyObject* item)
 {
-	PyNumberMethods *nb = item->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(item);
+	if (PyIndex_Check(item)) {
+		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 		if (i == -1 && PyErr_Occurred())
 			return NULL;
 		if (i < 0)
@@ -4228,12 +4225,17 @@
 	if (!result)
 		return NULL;
 
+	buf = PyString_AsString(result);
+	if (!buf) {
+		Py_DECREF(result);
+		return NULL;
+	}
+
 	/* To modify the string in-place, there can only be one reference. */
 	if (result->ob_refcnt != 1) {
 		PyErr_BadInternalCall();
 		return NULL;
 	}
-	buf = PyString_AsString(result);
 	llen = PyString_Size(result);
 	if (llen > PY_SSIZE_T_MAX) {
 		PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");

Modified: stackless/trunk/Objects/structseq.c
==============================================================================
--- stackless/trunk/Objects/structseq.c	(original)
+++ stackless/trunk/Objects/structseq.c	Mon Aug 21 11:10:05 2006
@@ -215,6 +215,8 @@
 	PyObject *tup;
 	int result;
 	tup = make_tuple(obj);
+	if (!tup)
+		return -1;
 	result = PySequence_Contains(tup, o);
 	Py_DECREF(tup);
 	return result;
@@ -226,6 +228,8 @@
 	PyObject *tup;
 	long result;
 	tup = make_tuple((PyStructSequence*) obj);
+	if (!tup)
+		return -1;
 	result = PyObject_Hash(tup);
 	Py_DECREF(tup);
 	return result;

Modified: stackless/trunk/Objects/tupleobject.c
==============================================================================
--- stackless/trunk/Objects/tupleobject.c	(original)
+++ stackless/trunk/Objects/tupleobject.c	Mon Aug 21 11:10:05 2006
@@ -577,14 +577,11 @@
 	(objobjproc)tuplecontains,		/* sq_contains */
 };
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
-
 static PyObject*
 tuplesubscript(PyTupleObject* self, PyObject* item)
 {
-	PyNumberMethods *nb = item->ob_type->tp_as_number;
-	if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-		Py_ssize_t i = nb->nb_index(item);
+	if (PyIndex_Check(item)) {
+		Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
 		if (i == -1 && PyErr_Occurred())
 			return NULL;
 		if (i < 0)

Modified: stackless/trunk/Objects/typeobject.c
==============================================================================
--- stackless/trunk/Objects/typeobject.c	(original)
+++ stackless/trunk/Objects/typeobject.c	Mon Aug 21 11:10:05 2006
@@ -1497,7 +1497,7 @@
 
 	if (obj->ob_type->tp_weaklistoffset == 0) {
 		PyErr_SetString(PyExc_AttributeError,
-				"This object has no __weaklist__");
+				"This object has no __weakref__");
 		return NULL;
 	}
 	assert(obj->ob_type->tp_weaklistoffset > 0);
@@ -3591,7 +3591,7 @@
 
 	if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
 		return NULL;
-	i = PyNumber_Index(o);
+	i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
 	if (i == -1 && PyErr_Occurred())
 		return NULL;
 	return (*func)(self, i);
@@ -3602,7 +3602,7 @@
 {
 	Py_ssize_t i;
 
-	i = PyNumber_Index(arg);
+	i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
 	if (i == -1 && PyErr_Occurred())
 		return -1;
 	if (i < 0) {
@@ -4174,19 +4174,17 @@
 {
 	static PyObject *len_str;
 	PyObject *res = call_method(self, "__len__", &len_str, "()");
-	Py_ssize_t temp;
 	Py_ssize_t len;
 
 	if (res == NULL)
 		return -1;
-	temp = PyInt_AsSsize_t(res);
-	len = (int)temp;
+	len = PyInt_AsSsize_t(res);
 	Py_DECREF(res);
 	if (len == -1 && PyErr_Occurred())
 		return -1;
-#if SIZEOF_SIZE_T < SIZEOF_LONG
+#if SIZEOF_SIZE_T < SIZEOF_INT
 	/* Overflow check -- range of PyInt is more than C ssize_t */
-	if (len != temp) {
+	if (len != (int)len) {
 		PyErr_SetString(PyExc_OverflowError,
 			"__len__() should return 0 <= outcome < 2**31");
 		return -1;
@@ -4408,26 +4406,11 @@
 }
 
 
-static Py_ssize_t
+static PyObject *
 slot_nb_index(PyObject *self)
 {
 	static PyObject *index_str;
-	PyObject *temp = call_method(self, "__index__", &index_str, "()");
-	Py_ssize_t result;
-
-	if (temp == NULL)
-		return -1;
-	if (PyInt_CheckExact(temp) || PyLong_CheckExact(temp)) {
-		result = temp->ob_type->tp_as_number->nb_index(temp);
-	}
-	else {
-		PyErr_Format(PyExc_TypeError,
-			     "__index__ must return an int or a long, "
-			     "not '%.200s'", temp->ob_type->tp_name);
-		result = -1;
-	}
-	Py_DECREF(temp);
-	return result;
+	return call_method(self, "__index__", &index_str, "()");
 }
 
 
@@ -4633,7 +4616,10 @@
 		Py_DECREF(func);
 		if (res == NULL)
 			return -1;
-		h = PyInt_AsLong(res);
+		if (PyLong_Check(res))
+			h = PyLong_Type.tp_hash(res);
+		else
+			h = PyInt_AsLong(res);
 		Py_DECREF(res);
 	}
 	else {
@@ -5266,7 +5252,7 @@
 	       "oct(x)"),
 	UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
 	       "hex(x)"),
-	NBSLOT("__index__", nb_index, slot_nb_index, wrap_lenfunc,
+	NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc, 
 	       "x[y:z] <==> x[y.__index__():z.__index__()]"),
 	IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
 	       wrap_binaryfunc, "+"),

Modified: stackless/trunk/Objects/unicodeobject.c
==============================================================================
--- stackless/trunk/Objects/unicodeobject.c	(original)
+++ stackless/trunk/Objects/unicodeobject.c	Mon Aug 21 11:10:05 2006
@@ -5405,6 +5405,82 @@
     return -1;
 }
 
+PyObject *PyUnicode_RichCompare(PyObject *left,
+                                PyObject *right,
+                                int op)
+{
+    int result;
+
+    result = PyUnicode_Compare(left, right);
+    if (result == -1 && PyErr_Occurred())
+        goto onError;
+
+    /* Convert the return value to a Boolean */
+    switch (op) {
+    case Py_EQ:
+        result = (result == 0);
+        break;
+    case Py_NE:
+        result = (result != 0);
+        break;
+    case Py_LE:
+        result = (result <= 0);
+        break;
+    case Py_GE:
+        result = (result >= 0);
+        break;
+    case Py_LT:
+        result = (result == -1);
+        break;
+    case Py_GT:
+        result = (result == 1);
+        break;
+    }
+    return PyBool_FromLong(result);
+
+ onError:
+
+    /* Standard case
+
+       Type errors mean that PyUnicode_FromObject() could not convert
+       one of the arguments (usually the right hand side) to Unicode,
+       ie. we can't handle the comparison request. However, it is
+       possible that the other object knows a comparison method, which
+       is why we return Py_NotImplemented to give the other object a
+       chance.
+
+    */
+    if (PyErr_ExceptionMatches(PyExc_TypeError)) {
+        PyErr_Clear();
+        Py_INCREF(Py_NotImplemented);
+        return Py_NotImplemented;
+    }
+    if (op != Py_EQ && op != Py_NE)
+        return NULL;
+
+    /* Equality comparison.
+
+       This is a special case: we silence any PyExc_UnicodeDecodeError
+       and instead turn it into a PyErr_UnicodeWarning.
+
+    */
+    if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError))
+        return NULL;
+    PyErr_Clear();
+    if (PyErr_Warn(PyExc_UnicodeWarning, 
+                   (op == Py_EQ) ? 
+                   "Unicode equal comparison "
+                   "failed to convert both arguments to Unicode - "
+                   "interpreting them as being unequal" :
+                   "Unicode unequal comparison "
+                   "failed to convert both arguments to Unicode - "
+                   "interpreting them as being unequal"
+                   ) < 0)
+        return NULL;
+    result = (op == Py_NE);
+    return PyBool_FromLong(result);
+}
+
 int PyUnicode_Contains(PyObject *container,
 		       PyObject *element)
 {
@@ -6985,14 +7061,11 @@
     PyUnicode_Contains, 		/* sq_contains */
 };
 
-#define HASINDEX(o) PyType_HasFeature((o)->ob_type, Py_TPFLAGS_HAVE_INDEX)
-
 static PyObject*
 unicode_subscript(PyUnicodeObject* self, PyObject* item)
 {
-    PyNumberMethods *nb = item->ob_type->tp_as_number;
-    if (nb != NULL && HASINDEX(item) && nb->nb_index != NULL) {
-        Py_ssize_t i = nb->nb_index(item);
+    if (PyIndex_Check(item)) {
+        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
         if (i == -1 && PyErr_Occurred())
             return NULL;
         if (i < 0)
@@ -7862,7 +7935,7 @@
     0, 					/* tp_print */
     0,				 	/* tp_getattr */
     0, 					/* tp_setattr */
-    (cmpfunc) unicode_compare, 		/* tp_compare */
+    0, 					/* tp_compare */
     unicode_repr, 			/* tp_repr */
     &unicode_as_number, 		/* tp_as_number */
     &unicode_as_sequence, 		/* tp_as_sequence */
@@ -7878,7 +7951,7 @@
     unicode_doc,			/* tp_doc */
     0,					/* tp_traverse */
     0,					/* tp_clear */
-    0,					/* tp_richcompare */
+    PyUnicode_RichCompare,		/* tp_richcompare */
     0,					/* tp_weaklistoffset */
     0,					/* tp_iter */
     0,					/* tp_iternext */

Modified: stackless/trunk/PCbuild/_msi.vcproj
==============================================================================
--- stackless/trunk/PCbuild/_msi.vcproj	(original)
+++ stackless/trunk/PCbuild/_msi.vcproj	Mon Aug 21 11:10:05 2006
@@ -36,11 +36,11 @@
 			<Tool
 				Name="VCLinkerTool"
 				AdditionalDependencies="fci.lib msi.lib rpcrt4.lib"
-				OutputFile="./_msi.pyd"
+				OutputFile="./_msi_d.pyd"
 				LinkIncremental="1"
 				SuppressStartupBanner="TRUE"
 				GenerateDebugInformation="TRUE"
-				ProgramDatabaseFile=".\./_msi.pdb"
+				ProgramDatabaseFile=".\./_msi_d.pdb"
 				BaseAddress="0x1D160000"
 				ImportLibrary=".\./_msi.lib"
 				TargetMachine="1"/>

Modified: stackless/trunk/PCbuild/_ssl.mak
==============================================================================
--- stackless/trunk/PCbuild/_ssl.mak	(original)
+++ stackless/trunk/PCbuild/_ssl.mak	Mon Aug 21 11:10:05 2006
@@ -1,21 +1,37 @@
 
 !IFDEF DEBUG
-MODULE=_ssl_d.pyd
-TEMP_DIR=x86-temp-debug/_ssl
+SUFFIX=_d.pyd
+TEMP=x86-temp-debug/
 CFLAGS=/Od /Zi /MDd /LDd /DDEBUG /D_DEBUG /DWIN32
 SSL_LIB_DIR=$(SSL_DIR)/out32.dbg
 !ELSE
-MODULE=_ssl.pyd
-TEMP_DIR=x86-temp-release/_ssl
+SUFFIX=.pyd
+TEMP=x86-temp-release/
 CFLAGS=/Ox /MD /LD /DWIN32
 SSL_LIB_DIR=$(SSL_DIR)/out32
 !ENDIF
 
 INCLUDES=-I ../Include -I ../PC -I $(SSL_DIR)/inc32
-LIBS=gdi32.lib wsock32.lib user32.lib advapi32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib
 
-SOURCE=../Modules/_ssl.c $(SSL_LIB_DIR)/libeay32.lib $(SSL_LIB_DIR)/ssleay32.lib
+SSL_LIBS=gdi32.lib wsock32.lib user32.lib advapi32.lib /LIBPATH:$(SSL_LIB_DIR) libeay32.lib ssleay32.lib
+SSL_SOURCE=../Modules/_ssl.c 
 
-$(MODULE): $(SOURCE) ../PC/*.h ../Include/*.h
-    @if not exist "$(TEMP_DIR)/." mkdir "$(TEMP_DIR)"
-    cl /nologo $(SOURCE) $(CFLAGS) /Fo$(TEMP_DIR)\$*.obj $(INCLUDES) /link /out:$(MODULE) $(LIBS)
+HASH_LIBS=gdi32.lib user32.lib advapi32.lib /libpath:$(SSL_LIB_DIR) libeay32.lib
+HASH_SOURCE=../Modules/_hashopenssl.c 
+
+all: _ssl$(SUFFIX) _hashlib$(SUFFIX)
+
+# Split compile/link into two steps to better support VSExtComp
+_ssl$(SUFFIX): $(SSL_SOURCE) $(SSL_LIB_DIR)/libeay32.lib $(SSL_LIB_DIR)/ssleay32.lib ../PC/*.h ../Include/*.h
+	@if not exist "$(TEMP)/_ssl/." mkdir "$(TEMP)/_ssl"
+	cl /nologo /c $(SSL_SOURCE) $(CFLAGS) /Fo$(TEMP)\_ssl\$*.obj $(INCLUDES)
+	link /nologo @<<
+             /dll /out:_ssl$(SUFFIX) $(TEMP)\_ssl\$*.obj $(SSL_LIBS)
+<<
+
+_hashlib$(SUFFIX): $(HASH_SOURCE) $(SSL_LIB_DIR)/libeay32.lib ../PC/*.h ../Include/*.h
+    @if not exist "$(TEMP)/_hashlib/." mkdir "$(TEMP)/_hashlib"
+    cl /nologo /c $(HASH_SOURCE) $(CFLAGS) /Fo$(TEMP)\_hashlib\$*.obj $(INCLUDES) 
+    link /nologo @<<
+	/dll /out:_hashlib$(SUFFIX) $(HASH_LIBS) $(TEMP)\_hashlib\$*.obj
+<<

Modified: stackless/trunk/PCbuild/_ssl.vcproj
==============================================================================
--- stackless/trunk/PCbuild/_ssl.vcproj	(original)
+++ stackless/trunk/PCbuild/_ssl.vcproj	Mon Aug 21 11:10:05 2006
@@ -75,6 +75,9 @@
 		<File
 			RelativePath="..\Modules\_ssl.c">
 		</File>
+		<File
+			RelativePath="..\Modules\_hashopenssl.c">
+		</File>
 	</Files>
 	<Globals>
 	</Globals>

Modified: stackless/trunk/PCbuild/build_ssl.py
==============================================================================
--- stackless/trunk/PCbuild/build_ssl.py	(original)
+++ stackless/trunk/PCbuild/build_ssl.py	Mon Aug 21 11:10:05 2006
@@ -1,7 +1,7 @@
-# Script for building the _ssl module for Windows.
+# Script for building the _ssl and _hashlib modules for Windows.
 # Uses Perl to setup the OpenSSL environment correctly
 # and build OpenSSL, then invokes a simple nmake session
-# for _ssl.pyd itself.
+# for the actual _ssl.pyd and _hashlib.pyd DLLs.
 
 # THEORETICALLY, you can:
 # * Unpack the latest SSL release one level above your main Python source
@@ -10,8 +10,8 @@
 # * Install ActivePerl and ensure it is somewhere on your path.
 # * Run this script from the PCBuild directory.
 #
-# it should configure and build SSL, then build the ssl Python extension
-# without intervention.
+# it should configure and build SSL, then build the _ssl and _hashlib
+# Python extensions without intervention.
 
 import os, sys, re
 
@@ -59,7 +59,8 @@
     candidates = []
     for s in sources:
         try:
-            s = os.path.abspath(s)
+            # note: do not abspath s; the build will fail if any
+            # higher up directory name has spaces in it.
             fnames = os.listdir(s)
         except os.error:
             fnames = []
@@ -82,31 +83,9 @@
         print "Found an SSL directory at '%s'" % (best_name,)
     else:
         print "Could not find an SSL directory in '%s'" % (sources,)
+    sys.stdout.flush()
     return best_name
 
-def run_32all_py():
-    # ms\32all.bat will reconfigure OpenSSL and then try to build
-    # all outputs (debug/nondebug/dll/lib).  So we filter the file
-    # to exclude any "nmake" commands and then execute.
-    tempname = "ms\\32all_py.bat"
-
-    in_bat  = open("ms\\32all.bat")
-    temp_bat = open(tempname,"w")
-    while 1:
-        cmd = in_bat.readline()
-        print 'cmd', repr(cmd)
-        if not cmd: break
-        if cmd.strip()[:5].lower() == "nmake":
-            continue
-        temp_bat.write(cmd)
-    in_bat.close()
-    temp_bat.close()
-    os.system(tempname)
-    try:
-        os.remove(tempname)
-    except:
-        pass
-
 def run_configure(configure, do_script):
     os.system("perl Configure "+configure)
     os.system(do_script)
@@ -117,12 +96,14 @@
         arch = "x86"
         debug = False
         configure = "VC-WIN32"
-        makefile = "32.mak"
+        do_script = "ms\\do_masm"
+        makefile = "ms\\nt.mak"
     elif sys.argv[1] == "Debug":
         arch = "x86"
         debug = True
         configure = "VC-WIN32"
-        makefile="d32.mak"
+        do_script = "ms\\do_masm"
+        makefile="ms\\d32.mak"
     elif sys.argv[1] == "ReleaseItanium":
         arch = "ia64"
         debug = False
@@ -148,8 +129,9 @@
         sys.exit(1)
 
     print "Found a working perl at '%s'" % (perl,)
+    sys.stdout.flush()
     # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live.
-    ssl_dir = find_best_ssl_dir(("../..",))
+    ssl_dir = find_best_ssl_dir(("..\\..",))
     if ssl_dir is None:
         sys.exit(1)
 
@@ -159,29 +141,35 @@
         # If the ssl makefiles do not exist, we invoke Perl to generate them.
         if not os.path.isfile(makefile):
             print "Creating the makefiles..."
+            sys.stdout.flush()
             # Put our working Perl at the front of our path
-            os.environ["PATH"] = os.path.split(perl)[0] + \
+            os.environ["PATH"] = os.path.dirname(perl) + \
                                           os.pathsep + \
                                           os.environ["PATH"]
-            if arch=="x86":
-                run_32all_py()
-            else:
-                run_configure(configure, do_script)
+            if arch=="x86" and debug:
+                # the do_masm script in openssl doesn't generate a debug
+                # build makefile so we generate it here:
+                os.system("perl util\mk1mf.pl debug "+configure+" >"+makefile)
+            run_configure(configure, do_script)
 
         # Now run make.
         print "Executing nmake over the ssl makefiles..."
-        rc = os.system("nmake /nologo -f "+makefile)
+        sys.stdout.flush()
+        rc = os.system("nmake /nologo PERL=\"%s\" -f \"%s\"" %(perl, makefile))
         if rc:
-            print "Executing d32.mak failed"
+            print "Executing "+makefile+" failed"
             print rc
             sys.exit(rc)
     finally:
         os.chdir(old_cd)
     # And finally, we can build the _ssl module itself for Python.
-    defs = "SSL_DIR=%s" % (ssl_dir,)
+    defs = "SSL_DIR=\"%s\"" % (ssl_dir,)
     if debug:
         defs = defs + " " + "DEBUG=1"
-    rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags)
+    makeCommand = 'nmake /nologo -f _ssl.mak ' + defs + " " + make_flags
+    print "Executing:", makeCommand
+    sys.stdout.flush()
+    rc = os.system(makeCommand)
     sys.exit(rc)
 
 if __name__=='__main__':

Modified: stackless/trunk/Parser/grammar.c
==============================================================================
--- stackless/trunk/Parser/grammar.c	(original)
+++ stackless/trunk/Parser/grammar.c	Mon Aug 21 11:10:05 2006
@@ -199,6 +199,10 @@
 			else
 				name_len = strlen(src);
 			dest = (char *)malloc(name_len + 1);
+			if (!dest) {
+				printf("Can't alloc dest '%s'\n", src);
+				return;
+			}
 			strncpy(dest, src, name_len);
 			dest[name_len] = '\0';
 			free(lb->lb_str);

Modified: stackless/trunk/Parser/parsetok.c
==============================================================================
--- stackless/trunk/Parser/parsetok.c	(original)
+++ stackless/trunk/Parser/parsetok.c	Mon Aug 21 11:10:05 2006
@@ -229,6 +229,11 @@
 		}
 	} else if (tok->encoding != NULL) {
 		node* r = PyNode_New(encoding_decl);
+		if (!r) {
+			err_ret->error = E_NOMEM;
+			n = NULL;
+			goto done;
+		}
 		r->n_str = tok->encoding;
 		r->n_nchildren = 1;
 		r->n_child = n;
@@ -236,6 +241,7 @@
 		n = r;
 	}
 
+done:
 	PyTokenizer_Free(tok);
 
 	return n;

Modified: stackless/trunk/Python/ast.c
==============================================================================
--- stackless/trunk/Python/ast.c	(original)
+++ stackless/trunk/Python/ast.c	Mon Aug 21 11:10:05 2006
@@ -2197,6 +2197,8 @@
             }
             else {
                 alias_ty a = alias_for_import_name(c, CHILD(n, 0));
+                if (!a)
+                    return NULL;
                 if (strcmp(STR(CHILD(n, 1)), "as") != 0) {
                     ast_error(n, "must use 'as' in import");
                     return NULL;

Modified: stackless/trunk/Python/bltinmodule.c
==============================================================================
--- stackless/trunk/Python/bltinmodule.c	(original)
+++ stackless/trunk/Python/bltinmodule.c	Mon Aug 21 11:10:05 2006
@@ -768,7 +768,7 @@
 	PyObject *d;
 
 	d = PyEval_GetGlobals();
-	Py_INCREF(d);
+	Py_XINCREF(d);
 	return d;
 }
 
@@ -1199,7 +1199,7 @@
 	PyObject *d;
 
 	d = PyEval_GetLocals();
-	Py_INCREF(d);
+	Py_XINCREF(d);
 	return d;
 }
 
@@ -1734,7 +1734,7 @@
 		if (PyFile_WriteString(" ", fout) != 0)
 			return NULL;
 	}
-	if (PyFile_Check(fin) && PyFile_Check(fout)
+	if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
             && isatty(fileno(PyFile_AsFile(fin)))
             && isatty(fileno(PyFile_AsFile(fout)))) {
 		PyObject *po;

Modified: stackless/trunk/Python/ceval.c
==============================================================================
--- stackless/trunk/Python/ceval.c	(original)
+++ stackless/trunk/Python/ceval.c	Mon Aug 21 11:10:05 2006
@@ -2900,6 +2900,7 @@
 		return NULL;
 	}
 
+	assert(tstate != NULL);
 	assert(globals != NULL);
 	f = PyFrame_New(tstate, co, globals, locals);
 	if (f == NULL)
@@ -3954,6 +3955,7 @@
 		   PyFrame_New() that doesn't take locals, but does
 		   take builtins without sanity checking them.
 		*/
+		assert(tstate != NULL);
 		f = PyFrame_New(tstate, co, globals, NULL);
 		if (f == NULL)
 			return NULL;
@@ -3977,7 +3979,6 @@
 #else
 		retval = PyEval_EvalFrameEx(f,0);
 #endif
-		assert(tstate != NULL);
 		++tstate->recursion_depth;
 		Py_DECREF(f);
 		--tstate->recursion_depth;
@@ -4202,12 +4203,14 @@
 	if (v != NULL) {
 		Py_ssize_t x;
 		if (PyInt_Check(v)) {
-			x = PyInt_AsSsize_t(v);
+			/* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
+			   however, it looks like it should be AsSsize_t.
+			   There should be a comment here explaining why.
+			*/
+			x = PyInt_AS_LONG(v);
 		}
-		else if (v->ob_type->tp_as_number &&
-			 PyType_HasFeature(v->ob_type, Py_TPFLAGS_HAVE_INDEX)
-			 && v->ob_type->tp_as_number->nb_index) {
-			x = v->ob_type->tp_as_number->nb_index(v);
+		else if (PyIndex_Check(v)) {
+			x = PyNumber_AsSsize_t(v, NULL);
 			if (x == -1 && PyErr_Occurred())
 				return 0;
 		}
@@ -4223,10 +4226,8 @@
 }
 
 #undef ISINDEX
-#define ISINDEX(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x) || \
-		    ((x)->ob_type->tp_as_number && \
-                     PyType_HasFeature((x)->ob_type, Py_TPFLAGS_HAVE_INDEX) \
-		     && (x)->ob_type->tp_as_number->nb_index))
+#define ISINDEX(x) ((x) == NULL || \
+		    PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
 
 static PyObject *
 apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
@@ -4466,6 +4467,11 @@
 			locals = PyEval_GetLocals();
 			plain = 1;
 		}
+		if (!globals || !locals) {
+			PyErr_SetString(PyExc_SystemError,
+					"globals and locals cannot be NULL");
+			return -1;
+		}
 	}
 	else if (locals == Py_None)
 		locals = globals;
@@ -4561,6 +4567,14 @@
 {
 	/* This function implements 'variable += expr' when both arguments
 	   are strings. */
+	Py_ssize_t v_len = PyString_GET_SIZE(v);
+	Py_ssize_t w_len = PyString_GET_SIZE(w);
+	Py_ssize_t new_len = v_len + w_len;
+	if (new_len < 0) {
+		PyErr_SetString(PyExc_OverflowError,
+				"strings are too large to concat");
+		return NULL;
+	}
 
 	if (v->ob_refcnt == 2) {
 		/* In the common case, there are 2 references to the value
@@ -4605,9 +4619,7 @@
 		/* Now we own the last reference to 'v', so we can resize it
 		 * in-place.
 		 */
-		Py_ssize_t v_len = PyString_GET_SIZE(v);
-		Py_ssize_t w_len = PyString_GET_SIZE(w);
-		if (_PyString_Resize(&v, v_len + w_len) != 0) {
+		if (_PyString_Resize(&v, new_len) != 0) {
 			/* XXX if _PyString_Resize() fails, 'v' has been
 			 * deallocated so it cannot be put back into 'variable'.
 			 * The MemoryError is raised when there is no value in

Modified: stackless/trunk/Python/compile.c
==============================================================================
--- stackless/trunk/Python/compile.c	(original)
+++ stackless/trunk/Python/compile.c	Mon Aug 21 11:10:05 2006
@@ -143,7 +143,7 @@
 	PyFutureFeatures *c_future; /* pointer to module's __future__ */
 	PyCompilerFlags *c_flags;
 
-	int c_interactive;
+	int c_interactive;	 /* true if in interactive mode */
 	int c_nestlevel;
 
 	struct compiler_unit *u; /* compiler state for current block */
@@ -204,8 +204,8 @@
 	const char *p, *name = PyString_AsString(ident);
 	char *buffer;
 	size_t nlen, plen;
-	if (privateobj == NULL || name == NULL || name[0] != '_' ||
-            name[1] != '_') {
+	if (privateobj == NULL || !PyString_Check(privateobj) ||
+	    name == NULL || name[0] != '_' || name[1] != '_') {
 		Py_INCREF(ident);
 		return ident;
 	}
@@ -1990,11 +1990,8 @@
 	n = asdl_seq_LEN(s->v.FunctionDef.body);
 	/* if there was a docstring, we need to skip the first statement */
 	for (i = docstring; i < n; i++) {
-		stmt_ty s2 = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
-		if (i == 0 && s2->kind == Expr_kind &&
-		    s2->v.Expr.value->kind == Str_kind)
-			continue;
-		VISIT_IN_SCOPE(c, stmt, s2);
+		st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
+		VISIT_IN_SCOPE(c, stmt, st);
 	}
 	co = assemble(c, 1);
 	compiler_exit_scope(c);
@@ -2217,6 +2214,10 @@
 	VISIT(c, expr, s->v.For.iter);
 	ADDOP(c, GET_ITER);
 	compiler_use_next_block(c, start);
+	/* XXX(nnorwitz): is there a better way to handle this?
+	   for loops are special, we want to be able to trace them
+	   each time around, so we need to set an extra line number. */
+	c->u->u_lineno_set = false;
 	ADDOP_JREL(c, FOR_ITER, cleanup);
 	VISIT(c, expr, s->v.For.target);
 	VISIT_SEQ(c, stmt, s->v.For.body);
@@ -2744,11 +2745,13 @@
 	case Global_kind:
 		break;
 	case Expr_kind:
-		VISIT(c, expr, s->v.Expr.value);
 		if (c->c_interactive && c->c_nestlevel <= 1) {
+			VISIT(c, expr, s->v.Expr.value);
 			ADDOP(c, PRINT_EXPR);
 		}
-		else {
+		else if (s->v.Expr.value->kind != Str_kind &&
+			 s->v.Expr.value->kind != Num_kind) {
+			VISIT(c, expr, s->v.Expr.value);
 			ADDOP(c, POP_TOP);
 		}
 		break;
@@ -4139,7 +4142,10 @@
 	assert(d_bytecode >= 0);
 	assert(d_lineno >= 0);
 
-	if (d_lineno == 0)
+	/* XXX(nnorwitz): is there a better way to handle this?
+	   for loops are special, we want to be able to trace them
+	   each time around, so we need to set an extra line number. */
+	if (d_lineno == 0 && i->i_opcode != FOR_ITER)
 		return 1;
 
 	if (d_bytecode > 255) {
@@ -4444,6 +4450,41 @@
 	return co;
 }
 
+
+/* For debugging purposes only */
+#if 0
+static void
+dump_instr(const struct instr *i)
+{
+	const char *jrel = i->i_jrel ? "jrel " : "";
+	const char *jabs = i->i_jabs ? "jabs " : "";
+	char arg[128];
+
+	*arg = '\0';
+	if (i->i_hasarg)
+		sprintf(arg, "arg: %d ", i->i_oparg);
+
+	fprintf(stderr, "line: %d, opcode: %d %s%s%s\n", 
+			i->i_lineno, i->i_opcode, arg, jabs, jrel);
+}
+
+static void
+dump_basicblock(const basicblock *b)
+{
+	const char *seen = b->b_seen ? "seen " : "";
+	const char *b_return = b->b_return ? "return " : "";
+	fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
+		b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
+	if (b->b_instr) {
+		int i;
+		for (i = 0; i < b->b_iused; i++) {
+			fprintf(stderr, "  [%02d] ", i);
+			dump_instr(b->b_instr + i);
+		}
+	}
+}
+#endif
+
 static PyCodeObject *
 assemble(struct compiler *c, int addNone)
 {

Modified: stackless/trunk/Python/errors.c
==============================================================================
--- stackless/trunk/Python/errors.c	(original)
+++ stackless/trunk/Python/errors.c	Mon Aug 21 11:10:05 2006
@@ -664,7 +664,7 @@
 
 #undef PyErr_Warn
 
-int
+PyAPI_FUNC(int)
 PyErr_Warn(PyObject *category, char *message)
 {
 	return PyErr_WarnEx(category, message, 1);

Modified: stackless/trunk/Python/getargs.c
==============================================================================
--- stackless/trunk/Python/getargs.c	(original)
+++ stackless/trunk/Python/getargs.c	Mon Aug 21 11:10:05 2006
@@ -206,6 +206,9 @@
 			if (level == 0)
 				max++;
 			level++;
+			if (level >= 30)
+				Py_FatalError("too many tuple nesting levels "
+					      "in argument format string");
 			break;
 		case ')':
 			if (level == 0)

Modified: stackless/trunk/Python/import.c
==============================================================================
--- stackless/trunk/Python/import.c	(original)
+++ stackless/trunk/Python/import.c	Mon Aug 21 11:10:05 2006
@@ -62,9 +62,11 @@
        Python 2.5a0: 62092 (changed WITH_CLEANUP opcode)
        Python 2.5b3: 62101 (fix wrong code: for x, in ...)
        Python 2.5b3: 62111 (fix wrong code: x += yield)
+       Python 2.5c1: 62121 (fix wrong lnotab with for loops and
+       			    storing constants that should have been removed)
 .
 */
-#define MAGIC (62111 | ((long)'\r'<<16) | ((long)'\n'<<24))
+#define MAGIC (62121 | ((long)'\r'<<16) | ((long)'\n'<<24))
 
 /* Magic word as global; note that _PyImport_Init() can change the
    value of this global to accommodate for alterations of how the
@@ -931,7 +933,8 @@
 		if (Py_VerboseFlag)
 			PySys_WriteStderr("import %s # from %s\n",
 				name, pathname);
-		write_compiled_module(co, cpathname, mtime);
+		if (cpathname)
+			write_compiled_module(co, cpathname, mtime);
 	}
 	m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
 	Py_DECREF(co);
@@ -1230,6 +1233,8 @@
 	for (i = 0; i < npath; i++) {
 		PyObject *copy = NULL;
 		PyObject *v = PyList_GetItem(path, i);
+		if (!v)
+			return NULL;
 #ifdef Py_USING_UNICODE
 		if (PyUnicode_Check(v)) {
 			copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
@@ -3042,6 +3047,8 @@
 	if (m == NULL)
 		goto failure;
 	d = PyModule_GetDict(m);
+	if (d == NULL)
+		goto failure;
 
 	if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
 	if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;

Modified: stackless/trunk/Python/marshal.c
==============================================================================
--- stackless/trunk/Python/marshal.c	(original)
+++ stackless/trunk/Python/marshal.c	Mon Aug 21 11:10:05 2006
@@ -213,6 +213,10 @@
 			w_byte(TYPE_COMPLEX, p);
 			temp = (PyFloatObject*)PyFloat_FromDouble(
 				PyComplex_RealAsDouble(v));
+			if (!temp) {
+				p->error = 1;
+				return;
+			}
 			PyFloat_AsReprString(buf, temp);
 			Py_DECREF(temp);
 			n = strlen(buf);
@@ -220,6 +224,10 @@
 			w_string(buf, (int)n, p);
 			temp = (PyFloatObject*)PyFloat_FromDouble(
 				PyComplex_ImagAsDouble(v));
+			if (!temp) {
+				p->error = 1;
+				return;
+			}
 			PyFloat_AsReprString(buf, temp);
 			Py_DECREF(temp);
 			n = strlen(buf);

Modified: stackless/trunk/Python/pystate.c
==============================================================================
--- stackless/trunk/Python/pystate.c	(original)
+++ stackless/trunk/Python/pystate.c	Mon Aug 21 11:10:05 2006
@@ -361,28 +361,43 @@
 /* Asynchronously raise an exception in a thread.
    Requested by Just van Rossum and Alex Martelli.
    To prevent naive misuse, you must write your own extension
-   to call this.  Must be called with the GIL held.
-   Returns the number of tstates modified; if it returns a number
-   greater than one, you're in trouble, and you should call it again
-   with exc=NULL to revert the effect.  This raises no exceptions. */
+   to call this, or use ctypes.  Must be called with the GIL held.
+   Returns the number of tstates modified (normally 1, but 0 if `id` didn't
+   match any known thread id).  Can be called with exc=NULL to clear an
+   existing async exception.  This raises no exceptions. */
 
 int
 PyThreadState_SetAsyncExc(long id, PyObject *exc) {
 	PyThreadState *tstate = PyThreadState_GET();
 	PyInterpreterState *interp = tstate->interp;
 	PyThreadState *p;
-	int count = 0;
+
+	/* Although the GIL is held, a few C API functions can be called
+	 * without the GIL held, and in particular some that create and
+	 * destroy thread and interpreter states.  Those can mutate the
+	 * list of thread states we're traversing, so to prevent that we lock
+	 * head_mutex for the duration.
+	 */
 	HEAD_LOCK();
 	for (p = interp->tstate_head; p != NULL; p = p->next) {
-		if (p->thread_id != id)
-			continue;
-		Py_CLEAR(p->async_exc);
-		Py_XINCREF(exc);
-		p->async_exc = exc;
-		count += 1;
+		if (p->thread_id == id) {
+			/* Tricky:  we need to decref the current value
+			 * (if any) in p->async_exc, but that can in turn
+			 * allow arbitrary Python code to run, including
+			 * perhaps calls to this function.  To prevent
+			 * deadlock, we need to release head_mutex before
+			 * the decref.
+			 */
+			PyObject *old_exc = p->async_exc;
+			Py_XINCREF(exc);
+			p->async_exc = exc;
+			HEAD_UNLOCK();
+			Py_XDECREF(old_exc);
+			return 1;
+		}
 	}
 	HEAD_UNLOCK();
-	return count;
+	return 0;
 }
 
 

Modified: stackless/trunk/Python/pythonrun.c
==============================================================================
--- stackless/trunk/Python/pythonrun.c	(original)
+++ stackless/trunk/Python/pythonrun.c	Mon Aug 21 11:10:05 2006
@@ -211,12 +211,16 @@
 	if (bimod == NULL)
 		Py_FatalError("Py_Initialize: can't initialize __builtin__");
 	interp->builtins = PyModule_GetDict(bimod);
+	if (interp->builtins == NULL)
+		Py_FatalError("Py_Initialize: can't initialize builtins dict");
 	Py_INCREF(interp->builtins);
 
 	sysmod = _PySys_Init();
 	if (sysmod == NULL)
 		Py_FatalError("Py_Initialize: can't initialize sys");
 	interp->sysdict = PyModule_GetDict(sysmod);
+	if (interp->sysdict == NULL)
+		Py_FatalError("Py_Initialize: can't initialize sys dict");
 	Py_INCREF(interp->sysdict);
 	_PyImport_FixupExtension("sys", "sys");
 	PySys_SetPath(Py_GetPath());

Modified: stackless/trunk/Python/symtable.c
==============================================================================
--- stackless/trunk/Python/symtable.c	(original)
+++ stackless/trunk/Python/symtable.c	Mon Aug 21 11:10:05 2006
@@ -915,6 +915,8 @@
 	PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
 		      ++st->st_cur->ste_tmpname);
 	tmp = PyString_InternFromString(tmpname);
+	if (!tmp)
+		return 0;
 	if (!symtable_add_def(st, tmp, DEF_LOCAL))
 		return 0;
 	Py_DECREF(tmp);
@@ -1323,8 +1325,11 @@
 	PyObject *name = (a->asname == NULL) ? a->name : a->asname;
 	const char *base = PyString_AS_STRING(name);
 	char *dot = strchr(base, '.');
-	if (dot)
+	if (dot) {
 		store_name = PyString_FromStringAndSize(base, dot - base);
+		if (!store_name)
+			return 0;
+	}
 	else {
 		store_name = name;
 		Py_INCREF(store_name);

Modified: stackless/trunk/README
==============================================================================
--- stackless/trunk/README	(original)
+++ stackless/trunk/README	Mon Aug 21 11:10:05 2006
@@ -1,5 +1,5 @@
-This is Python version 2.5 beta 3
-=================================
+This is Python version 2.5 rc 1
+===============================
 
 Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python Software Foundation.
 All rights reserved.

Modified: stackless/trunk/Tools/msi/msi.py
==============================================================================
--- stackless/trunk/Tools/msi/msi.py	(original)
+++ stackless/trunk/Tools/msi/msi.py	Mon Aug 21 11:10:05 2006
@@ -89,7 +89,8 @@
     '_msi.pyd',
     '_ctypes.pyd',
     '_ctypes_test.pyd',
-    '_sqlite3.pyd'
+    '_sqlite3.pyd',
+    '_hashlib.pyd'
 ]
 
 # Well-known component UUIDs

Modified: stackless/trunk/configure
==============================================================================
--- stackless/trunk/configure	(original)
+++ stackless/trunk/configure	Mon Aug 21 11:10:05 2006
@@ -1599,7 +1599,7 @@
   # disables platform specific features beyond repair.
   # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE
   # has no effect, don't bother defining them
-  Darwin/[78].*)
+  Darwin/[789].*)
     define_xopen_source=no
     ;;
 

Modified: stackless/trunk/configure.in
==============================================================================
--- stackless/trunk/configure.in	(original)
+++ stackless/trunk/configure.in	Mon Aug 21 11:10:05 2006
@@ -247,7 +247,7 @@
   # disables platform specific features beyond repair.
   # On Mac OS X 10.3, defining _POSIX_C_SOURCE or _XOPEN_SOURCE 
   # has no effect, don't bother defining them
-  Darwin/@<:@78@:>@.*)
+  Darwin/@<:@789@:>@.*)
     define_xopen_source=no
     ;;
 

Modified: stackless/trunk/setup.py
==============================================================================
--- stackless/trunk/setup.py	(original)
+++ stackless/trunk/setup.py	Mon Aug 21 11:10:05 2006
@@ -902,8 +902,12 @@
 
         # Curses support, requiring the System V version of curses, often
         # provided by the ncurses library.
+        panel_library = 'panel'
         if (self.compiler.find_library_file(lib_dirs, 'ncursesw')):
             curses_libs = ['ncursesw']
+            # Bug 1464056: If _curses.so links with ncursesw,
+            # _curses_panel.so must link with panelw.
+            panel_library = 'panelw'
             exts.append( Extension('_curses', ['_cursesmodule.c'],
                                    libraries = curses_libs) )
         elif (self.compiler.find_library_file(lib_dirs, 'ncurses')):
@@ -926,9 +930,9 @@
 
         # If the curses module is enabled, check for the panel module
         if (module_enabled(exts, '_curses') and
-            self.compiler.find_library_file(lib_dirs, 'panel')):
+            self.compiler.find_library_file(lib_dirs, panel_library)):
             exts.append( Extension('_curses_panel', ['_curses_panel.c'],
-                                   libraries = ['panel'] + curses_libs) )
+                                   libraries = [panel_library] + curses_libs) )
 
 
         # Andrew Kuchling's zlib module.  Note that some versions of zlib
@@ -1349,6 +1353,7 @@
         self.use_system_libffi = False
         include_dirs = []
         extra_compile_args = []
+        extra_link_args = []
         sources = ['_ctypes/_ctypes.c',
                    '_ctypes/callbacks.c',
                    '_ctypes/callproc.c',
@@ -1363,9 +1368,21 @@
 # XXX Is this still needed?
 ##            extra_link_args.extend(['-read_only_relocs', 'warning'])
 
+        elif sys.platform == 'sunos5':
+            # XXX This shouldn't be necessary; it appears that some
+            # of the assembler code is non-PIC (i.e. it has relocations
+            # when it shouldn't. The proper fix would be to rewrite
+            # the assembler code to be PIC.
+            # This only works with GCC; the Sun compiler likely refuses
+            # this option. If you want to compile ctypes with the Sun
+            # compiler, please research a proper solution, instead of
+            # finding some -z option for the Sun compiler.
+            extra_link_args.append('-mimpure-text')
+
         ext = Extension('_ctypes',
                         include_dirs=include_dirs,
                         extra_compile_args=extra_compile_args,
+                        extra_link_args=extra_link_args,
                         libraries=[],
                         sources=sources,
                         depends=depends)

-------------- next part --------------
_______________________________________________
Stackless-checkins mailing list
Stackless-checkins at stackless.com
http://www.stackless.com/mailman/listinfo/stackless-checkins


More information about the Stackless-checkins mailing list