An interpreted, interactive, object-oriented programming language
CentOS Buildsys
2013-11-07 6e8c2f17a5493dc1c0002c232ef09e77adc37709
import python-2.7.5-10.el7.src.rpm
69 files added
1 files deleted
8664 ■■■■■ changed files
.python.metadata 1 ●●●● patch | view | raw | blame | history
README.md 5 ●●●●● patch | view | raw | blame | history
SOURCES/00001-pydocnogui.patch 38 ●●●●● patch | view | raw | blame | history
SOURCES/00055-systemtap.patch 198 ●●●●● patch | view | raw | blame | history
SOURCES/00104-lib64-fix-for-test_install.patch 13 ●●●●● patch | view | raw | blame | history
SOURCES/00111-no-static-lib.patch 50 ●●●●● patch | view | raw | blame | history
SOURCES/00113-more-configuration-flags.patch 50 ●●●●● patch | view | raw | blame | history
SOURCES/00114-statvfs-f_flag-constants.patch 47 ●●●●● patch | view | raw | blame | history
SOURCES/00121-add-Modules-to-build-path.patch 13 ●●●●● patch | view | raw | blame | history
SOURCES/00125-less-verbose-COUNT_ALLOCS.patch 20 ●●●●● patch | view | raw | blame | history
SOURCES/00131-disable-tests-in-test_io.patch 11 ●●●●● patch | view | raw | blame | history
SOURCES/00132-add-rpmbuild-hooks-to-unittest.patch 68 ●●●●● patch | view | raw | blame | history
SOURCES/00133-skip-test_dl.patch 13 ●●●●● patch | view | raw | blame | history
SOURCES/00134-fix-COUNT_ALLOCS-failure-in-test_sys.patch 14 ●●●●● patch | view | raw | blame | history
SOURCES/00135-skip-test-within-test_weakref-in-debug-build.patch 18 ●●●●● patch | view | raw | blame | history
SOURCES/00136-skip-tests-of-seeking-stdin-in-rpmbuild.patch 22 ●●●●● patch | view | raw | blame | history
SOURCES/00137-skip-distutils-tests-that-fail-in-rpmbuild.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/00138-fix-distutils-tests-in-debug-build.patch 68 ●●●●● patch | view | raw | blame | history
SOURCES/00139-skip-test_float-known-failure-on-arm.patch 11 ●●●●● patch | view | raw | blame | history
SOURCES/00140-skip-test_ctypes-known-failure-on-sparc.patch 11 ●●●●● patch | view | raw | blame | history
SOURCES/00141-fix-test_gc_with_COUNT_ALLOCS.patch 24 ●●●●● patch | view | raw | blame | history
SOURCES/00142-skip-failing-pty-tests-in-rpmbuild.patch 22 ●●●●● patch | view | raw | blame | history
SOURCES/00143-tsc-on-ppc.patch 58 ●●●●● patch | view | raw | blame | history
SOURCES/00144-no-gdbm.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/00146-hashlib-fips.patch 729 ●●●●● patch | view | raw | blame | history
SOURCES/00147-add-debug-malloc-stats.patch 711 ●●●●● patch | view | raw | blame | history
SOURCES/00153-fix-test_gdb-noise.patch 31 ●●●●● patch | view | raw | blame | history
SOURCES/00155-avoid-ctypes-thunks.patch 15 ●●●●● patch | view | raw | blame | history
SOURCES/00156-gdb-autoload-safepath.patch 52 ●●●●● patch | view | raw | blame | history
SOURCES/00157-uid-gid-overflows.patch 49 ●●●●● patch | view | raw | blame | history
SOURCES/00165-crypt-module-salt-backport.patch 285 ●●●●● patch | view | raw | blame | history
SOURCES/00166-fix-fake-repr-in-gdb-hooks.patch 125 ●●●●● patch | view | raw | blame | history
SOURCES/00167-disable-stack-navigation-tests-when-optimized-in-test_gdb.patch 43 ●●●●● patch | view | raw | blame | history
SOURCES/00168-distutils-cflags.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/00169-avoid-implicit-usage-of-md5-in-multiprocessing.patch 41 ●●●●● patch | view | raw | blame | history
SOURCES/00170-gc-assertions.patch 276 ●●●●● patch | view | raw | blame | history
SOURCES/00173-workaround-ENOPROTOOPT-in-bind_port.patch 13 ●●●●● patch | view | raw | blame | history
SOURCES/00174-fix-for-usr-move.patch 28 ●●●●● patch | view | raw | blame | history
SOURCES/00180-python-add-support-for-ppc64p7.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/00181-allow-arbitrary-timeout-in-condition-wait.patch 70 ●●●●● patch | view | raw | blame | history
SOURCES/00184-ctypes-should-build-with-libffi-multilib-wrapper.patch 13 ●●●●● patch | view | raw | blame | history
SOURCES/00185-urllib2-honors-noproxy-for-ftp.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/00186-memory-leak-marshalc.patch 57 ●●●●● patch | view | raw | blame | history
SOURCES/00187-add-RPATH-to-pyexpat.patch 25 ●●●●● patch | view | raw | blame | history
SOURCES/00188-CVE-2013-4238-hostname-check-bypass-in-SSL-module.patch 247 ●●●●● patch | view | raw | blame | history
SOURCES/00189-gdb-py-bt-dont-raise-exception-from-eval.patch 11 ●●●●● patch | view | raw | blame | history
SOURCES/00190-gdb-fix-ppc64-failures.patch 207 ●●●●● patch | view | raw | blame | history
SOURCES/00191-add-RPATH-to-elementtree.patch 21 ●●●●● patch | view | raw | blame | history
SOURCES/05000-autotool-intermediates.patch 216 ●●●●● patch | view | raw | blame | history
SOURCES/libpython.stp 17 ●●●●● patch | view | raw | blame | history
SOURCES/macros.python2 4 ●●●● patch | view | raw | blame | history
SOURCES/pyfuntop.stp 21 ●●●●● patch | view | raw | blame | history
SOURCES/pynche 2 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.5-cflags.patch 11 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.5.1-plural-fix.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.5.1-sqlite-encoding.patch 24 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.6-rpath.patch 12 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.6.4-distutils-rpath.patch 20 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7-lib64-sysconfig.patch 44 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7.1-config.patch 283 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7.1-fix_test_abc_with_COUNT_ALLOCS.patch 27 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7.2-add-extension-suffix-to-python-config.patch 18 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7.3-debug-build.patch 292 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7.3-lib64.patch 196 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7rc1-binutils-no-dep.patch 14 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7rc1-socketmodule-constants.patch 64 ●●●●● patch | view | raw | blame | history
SOURCES/python-2.7rc1-socketmodule-constants2.patch 19 ●●●●● patch | view | raw | blame | history
SOURCES/pythondeps.sh 32 ●●●●● patch | view | raw | blame | history
SOURCES/systemtap-example.stp 19 ●●●●● patch | view | raw | blame | history
SPECS/python.spec 3433 ●●●●● patch | view | raw | blame | history
.python.metadata
New file
@@ -0,0 +1 @@
b7389791f789625c2ba9d897aa324008ff482daf SOURCES/Python-2.7.5.tar.xz
README.md
File was deleted
SOURCES/00001-pydocnogui.patch
New file
@@ -0,0 +1,38 @@
diff -up Python-2.7.3/Lib/pydoc.py.no_gui Python-2.7.3/Lib/pydoc.py
--- Python-2.7.3/Lib/pydoc.py.no_gui    2012-04-09 19:07:31.000000000 -0400
+++ Python-2.7.3/Lib/pydoc.py    2013-02-19 13:48:44.480054515 -0500
@@ -19,9 +19,6 @@ of all available modules.
 Run "pydoc -p <port>" to start an HTTP server on a given port on the
 local machine to generate documentation web pages.
-For platforms without a command line, "pydoc -g" starts the HTTP server
-and also pops up a little window for controlling it.
-
 Run "pydoc -w <name>" to write out the HTML documentation for a module
 to a file named "<name>.html".
@@ -2290,9 +2287,6 @@ def cli():
         writing = 0
         for opt, val in opts:
-            if opt == '-g':
-                gui()
-                return
             if opt == '-k':
                 apropos(val)
                 return
@@ -2346,13 +2340,10 @@ def cli():
 %s -p <port>
     Start an HTTP server on the given port on the local machine.
-%s -g
-    Pop up a graphical interface for finding and serving documentation.
-
 %s -w <name> ...
     Write out the HTML documentation for a module to a file in the current
     directory.  If <name> contains a '%s', it is treated as a filename; if
     it names a directory, documentation is written for all the contents.
-""" % (cmd, os.sep, cmd, cmd, cmd, cmd, os.sep)
+""" % (cmd, os.sep, cmd, cmd, cmd, os.sep)
 if __name__ == '__main__': cli()
SOURCES/00055-systemtap.patch
New file
@@ -0,0 +1,198 @@
diff -up Python-2.7rc1/configure.ac.systemtap Python-2.7rc1/configure.ac
--- Python-2.7rc1/configure.ac.systemtap    2010-06-06 10:53:15.514975012 -0400
+++ Python-2.7rc1/configure.ac    2010-06-06 10:53:15.520974361 -0400
@@ -2616,6 +2616,38 @@ if test "$with_valgrind" != no; then
     )
 fi
+# Check for dtrace support
+AC_MSG_CHECKING(for --with-dtrace)
+AC_ARG_WITH(dtrace,
+            AC_HELP_STRING(--with(out)-dtrace, disable/enable dtrace support))
+
+if test ! -z "$with_dtrace"
+then
+    if dtrace -G -o /dev/null -s $srcdir/Include/pydtrace.d 2>/dev/null
+    then
+    AC_DEFINE(WITH_DTRACE, 1,
+     [Define if you want to compile in Dtrace support])
+    with_dtrace="Sun"
+    DTRACEOBJS="Python/dtrace.o"
+    DTRADEHDRS=""
+    elif dtrace -h -o /dev/null -s $srcdir/Include/pydtrace.d
+    then
+    AC_DEFINE(WITH_DTRACE, 1,
+     [Define if you want to compile in Dtrace support])
+    with_dtrace="Apple"
+    DTRACEOBJS=""
+    DTRADEHDRS="pydtrace.h"
+    else
+    with_dtrace="no"
+    fi
+else
+    with_dtrace="no"
+fi
+
+AC_MSG_RESULT($with_dtrace)
+AC_SUBST(DTRACEOBJS)
+AC_SUBST(DTRACEHDRS)
+
 # Check for --with-wctype-functions
 AC_MSG_CHECKING(for --with-wctype-functions)
 AC_ARG_WITH(wctype-functions,
diff -up Python-2.7rc1/Include/pydtrace.d.systemtap Python-2.7rc1/Include/pydtrace.d
--- Python-2.7rc1/Include/pydtrace.d.systemtap    2010-06-06 10:53:15.520974361 -0400
+++ Python-2.7rc1/Include/pydtrace.d    2010-06-06 10:53:15.520974361 -0400
@@ -0,0 +1,10 @@
+provider python {
+    probe function__entry(const char *, const char *, int);
+    probe function__return(const char *, const char *, int);
+};
+
+#pragma D attributes Evolving/Evolving/Common provider python provider
+#pragma D attributes Private/Private/Common provider python module
+#pragma D attributes Private/Private/Common provider python function
+#pragma D attributes Evolving/Evolving/Common provider python name
+#pragma D attributes Evolving/Evolving/Common provider python args
diff -up Python-2.7rc1/Makefile.pre.in.systemtap Python-2.7rc1/Makefile.pre.in
--- Python-2.7rc1/Makefile.pre.in.systemtap    2010-06-06 10:53:15.488978775 -0400
+++ Python-2.7rc1/Makefile.pre.in    2010-06-06 11:05:30.411100568 -0400
@@ -298,6 +298,7 @@ PYTHON_OBJS=    \
         Python/formatter_unicode.o \
         Python/formatter_string.o \
         Python/$(DYNLOADFILE) \
+        @DTRACEOBJS@ \
         $(LIBOBJS) \
         $(MACHDEP_OBJS) \
         $(THREADOBJ)
@@ -599,6 +600,18 @@ Python/formatter_unicode.o: $(srcdir)/Py
 Python/formatter_string.o: $(srcdir)/Python/formatter_string.c \
                 $(STRINGLIB_HEADERS)
+# Only needed with --with-dtrace
+buildinclude:
+    mkdir -p Include
+
+Include/pydtrace.h: buildinclude $(srcdir)/Include/pydtrace.d
+    dtrace -o $@ $(DFLAGS) -C -h -s $(srcdir)/Include/pydtrace.d
+
+Python/ceval.o: Include/pydtrace.h
+
+Python/dtrace.o: buildinclude $(srcdir)/Include/pydtrace.d Python/ceval.o
+    dtrace -o $@ $(DFLAGS) -C -G -s $(srcdir)/Include/pydtrace.d Python/ceval.o
+
 ############################################################################
 # Header files
@@ -1251,7 +1264,7 @@ Python/thread.o: @THREADHEADERS@
 .PHONY: frameworkinstall frameworkinstallframework frameworkinstallstructure
 .PHONY: frameworkinstallmaclib frameworkinstallapps frameworkinstallunixtools
 .PHONY: frameworkaltinstallunixtools recheck autoconf clean clobber distclean
-.PHONY: smelly funny patchcheck touch altmaninstall
+.PHONY: smelly funny patchcheck touch altmaninstall buildinclude
 .PHONY: gdbhooks
 # IF YOU PUT ANYTHING HERE IT WILL GO AWAY
diff -up Python-2.7rc1/pyconfig.h.in.systemtap Python-2.7rc1/pyconfig.h.in
--- Python-2.7rc1/pyconfig.h.in.systemtap    2010-05-08 07:04:18.000000000 -0400
+++ Python-2.7rc1/pyconfig.h.in    2010-06-06 10:53:15.521974070 -0400
@@ -1074,6 +1074,9 @@
 /* Define if you want documentation strings in extension modules */
 #undef WITH_DOC_STRINGS
+/* Define if you want to compile in Dtrace support */
+#undef WITH_DTRACE
+
 /* Define if you want to use the new-style (Openstep, Rhapsody, MacOS) dynamic
    linker (dyld) instead of the old-style (NextStep) dynamic linker (rld).
    Dyld is necessary to support frameworks. */
diff -up Python-2.7rc1/Python/ceval.c.systemtap Python-2.7rc1/Python/ceval.c
--- Python-2.7rc1/Python/ceval.c.systemtap    2010-05-09 10:46:46.000000000 -0400
+++ Python-2.7rc1/Python/ceval.c    2010-06-06 11:08:40.683100500 -0400
@@ -19,6 +19,10 @@
 #include <ctype.h>
+#ifdef WITH_DTRACE
+#include "pydtrace.h"
+#endif
+
 #ifndef WITH_TSC
 #define READ_TIMESTAMP(var)
@@ -671,6 +675,55 @@ PyEval_EvalCode(PyCodeObject *co, PyObje
                       NULL);
 }
+#ifdef WITH_DTRACE
+static void
+dtrace_entry(PyFrameObject *f)
+{
+    const char *filename;
+    const char *fname;
+    int lineno;
+
+    filename = PyString_AsString(f->f_code->co_filename);
+    fname = PyString_AsString(f->f_code->co_name);
+    lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
+
+    PYTHON_FUNCTION_ENTRY((char *)filename, (char *)fname, lineno);
+
+    /*
+     * Currently a USDT tail-call will not receive the correct arguments.
+     * Disable the tail call here.
+     */
+#if defined(__sparc)
+    asm("nop");
+#endif
+}
+
+static void
+dtrace_return(PyFrameObject *f)
+{
+    const char *filename;
+    const char *fname;
+    int lineno;
+
+    filename = PyString_AsString(f->f_code->co_filename);
+    fname = PyString_AsString(f->f_code->co_name);
+    lineno = PyCode_Addr2Line(f->f_code, f->f_lasti);
+    PYTHON_FUNCTION_RETURN((char *)filename, (char *)fname, lineno);
+
+    /*
+     * Currently a USDT tail-call will not receive the correct arguments.
+     * Disable the tail call here.
+     */
+#if defined(__sparc)
+    asm("nop");
+#endif
+}
+#else
+#define    PYTHON_FUNCTION_ENTRY_ENABLED() 0
+#define    PYTHON_FUNCTION_RETURN_ENABLED() 0
+#define    dtrace_entry(f)
+#define    dtrace_return(f)
+#endif
 /* Interpreter main loop */
@@ -909,6 +962,9 @@ PyEval_EvalFrameEx(PyFrameObject *f, int
         }
     }
+    if (PYTHON_FUNCTION_ENTRY_ENABLED())
+        dtrace_entry(f);
+
     co = f->f_code;
     names = co->co_names;
     consts = co->co_consts;
@@ -3000,6 +3056,9 @@ fast_yield:
     /* pop frame */
 exit_eval_frame:
+    if (PYTHON_FUNCTION_RETURN_ENABLED())
+        dtrace_return(f);
+
     Py_LeaveRecursiveCall();
     tstate->frame = f->f_back;
SOURCES/00104-lib64-fix-for-test_install.patch
New file
@@ -0,0 +1,13 @@
--- Python-2.7.2/Lib/distutils/tests/test_install.py.lib64    2011-09-08 17:51:57.851405376 -0400
+++ Python-2.7.2/Lib/distutils/tests/test_install.py    2011-09-08 18:40:46.754205096 -0400
@@ -41,8 +41,9 @@ class InstallTestCase(support.TempdirMan
             self.assertEqual(got, expected)
         libdir = os.path.join(destination, "lib", "python")
+        platlibdir = os.path.join(destination, "lib64", "python")
         check_path(cmd.install_lib, libdir)
-        check_path(cmd.install_platlib, libdir)
+        check_path(cmd.install_platlib, platlibdir)
         check_path(cmd.install_purelib, libdir)
         check_path(cmd.install_headers,
                    os.path.join(destination, "include", "python", "foopkg"))
SOURCES/00111-no-static-lib.patch
New file
@@ -0,0 +1,50 @@
diff -up Python-2.7.3/Makefile.pre.in.no-static-lib Python-2.7.3/Makefile.pre.in
--- Python-2.7.3/Makefile.pre.in.no-static-lib    2013-02-19 14:03:40.801993224 -0500
+++ Python-2.7.3/Makefile.pre.in    2013-02-19 14:04:44.070988898 -0500
@@ -397,7 +397,7 @@ coverage:
 # Build the interpreter
-$(BUILDPYTHON):    Modules/python.o $(LIBRARY) $(LDLIBRARY)
+$(BUILDPYTHON):    Modules/python.o $(LDLIBRARY)
         $(LINKCC) $(CFLAGS) $(LDFLAGS) $(LINKFORSHARED) -o $@ \
             Modules/python.o \
             $(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)
@@ -413,18 +413,6 @@ sharedmods: $(BUILDPYTHON)
     $(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' \
         $(PYTHON_FOR_BUILD) $(srcdir)/setup.py $$quiet build
-# Build static library
-# avoid long command lines, same as LIBRARY_OBJS
-$(LIBRARY): $(LIBRARY_OBJS)
-    -rm -f $@
-    $(AR) $(ARFLAGS) $@ Modules/getbuildinfo.o
-    $(AR) $(ARFLAGS) $@ $(PARSER_OBJS)
-    $(AR) $(ARFLAGS) $@ $(OBJECT_OBJS)
-    $(AR) $(ARFLAGS) $@ $(PYTHON_OBJS)
-    $(AR) $(ARFLAGS) $@ $(MODULE_OBJS) $(SIGNAL_OBJS)
-    $(AR) $(ARFLAGS) $@ $(MODOBJS)
-    $(RANLIB) $@
-
 libpython$(VERSION).so: $(LIBRARY_OBJS)
     if test $(INSTSONAME) != $(LDLIBRARY); then \
         $(BLDSHARED) -Wl,-h$(INSTSONAME) -o $(INSTSONAME) $(LIBRARY_OBJS) $(MODLIBS) $(SHLIBS) $(LIBC) $(LIBM) $(LDLAST); \
@@ -1021,18 +1009,6 @@ libainstall:    all python-config
         else    true; \
         fi; \
     done
-    @if test -d $(LIBRARY); then :; else \
-        if test "$(PYTHONFRAMEWORKDIR)" = no-framework; then \
-            if test "$(SO)" = .dll; then \
-                $(INSTALL_DATA) $(LDLIBRARY) $(DESTDIR)$(LIBPL) ; \
-            else \
-                $(INSTALL_DATA) $(LIBRARY) $(DESTDIR)$(LIBPL)/$(LIBRARY) ; \
-                $(RANLIB) $(DESTDIR)$(LIBPL)/$(LIBRARY) ; \
-            fi; \
-        else \
-            echo Skip install of $(LIBRARY) - use make frameworkinstall; \
-        fi; \
-    fi
     $(INSTALL_DATA) Modules/config.c $(DESTDIR)$(LIBPL)/config.c
     $(INSTALL_DATA) Modules/python.o $(DESTDIR)$(LIBPL)/python.o
     $(INSTALL_DATA) $(srcdir)/Modules/config.c.in $(DESTDIR)$(LIBPL)/config.c.in
SOURCES/00113-more-configuration-flags.patch
New file
@@ -0,0 +1,50 @@
diff -up Python-2.6.5/configure.ac.more-configuration-flags Python-2.6.5/configure.ac
--- Python-2.6.5/configure.ac.more-configuration-flags    2010-05-24 18:51:25.410111792 -0400
+++ Python-2.6.5/configure.ac    2010-05-24 18:59:23.954986388 -0400
@@ -2515,6 +2515,30 @@ else AC_MSG_RESULT(no)
 fi],
 [AC_MSG_RESULT(no)])
+AC_MSG_CHECKING(for --with-count-allocs)
+AC_ARG_WITH(count-allocs,
+[  --with(out)count-allocs  enable/disable per-type instance accounting], [
+if test "$withval" != no
+then
+  AC_DEFINE(COUNT_ALLOCS, 1,
+    [Define to keep records of the number of instances of each type])
+    AC_MSG_RESULT(yes)
+else AC_MSG_RESULT(no)
+fi],
+[AC_MSG_RESULT(no)])
+
+AC_MSG_CHECKING(for --with-call-profile)
+AC_ARG_WITH(call-profile,
+[  --with(out)-call-profile  enable/disable statistics on function call invocation], [
+if test "$withval" != no
+then
+  AC_DEFINE(CALL_PROFILE, 1,
+    [Define to keep records on function call invocation])
+    AC_MSG_RESULT(yes)
+else AC_MSG_RESULT(no)
+fi],
+[AC_MSG_RESULT(no)])
+
 # Check for Python-specific malloc support
 AC_MSG_CHECKING(for --with-pymalloc)
 AC_ARG_WITH(pymalloc,
diff -up Python-2.6.5/pyconfig.h.in.more-configuration-flags Python-2.6.5/pyconfig.h.in
--- Python-2.6.5/pyconfig.h.in.more-configuration-flags    2010-05-24 18:51:45.677988086 -0400
+++ Python-2.6.5/pyconfig.h.in    2010-05-24 19:00:44.163987730 -0400
@@ -1019,6 +1019,12 @@
 /* Define to profile with the Pentium timestamp counter */
 #undef WITH_TSC
+/* Define to keep records of the number of instances of each type */
+#undef COUNT_ALLOCS
+
+/* Define to keep records on function call invocation */
+#undef CALL_PROFILE
+
 /* Define if you want pymalloc to be disabled when running under valgrind */
 #undef WITH_VALGRIND
SOURCES/00114-statvfs-f_flag-constants.patch
New file
@@ -0,0 +1,47 @@
diff -up Python-2.7rc1/Modules/posixmodule.c.statvfs-f-flag-constants Python-2.7rc1/Modules/posixmodule.c
--- Python-2.7rc1/Modules/posixmodule.c.statvfs-f-flag-constants    2010-05-15 17:45:30.000000000 -0400
+++ Python-2.7rc1/Modules/posixmodule.c    2010-06-07 22:54:16.162068624 -0400
@@ -9174,6 +9174,43 @@ all_ins(PyObject *d)
 #endif
 #endif
+    /* These came from statvfs.h */
+#ifdef ST_RDONLY
+    if (ins(d, "ST_RDONLY", (long)ST_RDONLY)) return -1;
+#endif /* ST_RDONLY */
+#ifdef ST_NOSUID
+    if (ins(d, "ST_NOSUID", (long)ST_NOSUID)) return -1;
+#endif /* ST_NOSUID */
+
+    /* GNU extensions */
+#ifdef ST_NODEV
+    if (ins(d, "ST_NODEV", (long)ST_NODEV)) return -1;
+#endif /* ST_NODEV */
+#ifdef ST_NOEXEC
+    if (ins(d, "ST_NOEXEC", (long)ST_NOEXEC)) return -1;
+#endif /* ST_NOEXEC */
+#ifdef ST_SYNCHRONOUS
+    if (ins(d, "ST_SYNCHRONOUS", (long)ST_SYNCHRONOUS)) return -1;
+#endif /* ST_SYNCHRONOUS */
+#ifdef ST_MANDLOCK
+    if (ins(d, "ST_MANDLOCK", (long)ST_MANDLOCK)) return -1;
+#endif /* ST_MANDLOCK */
+#ifdef ST_WRITE
+    if (ins(d, "ST_WRITE", (long)ST_WRITE)) return -1;
+#endif /* ST_WRITE */
+#ifdef ST_APPEND
+    if (ins(d, "ST_APPEND", (long)ST_APPEND)) return -1;
+#endif /* ST_APPEND */
+#ifdef ST_NOATIME
+    if (ins(d, "ST_NOATIME", (long)ST_NOATIME)) return -1;
+#endif /* ST_NOATIME */
+#ifdef ST_NODIRATIME
+    if (ins(d, "ST_NODIRATIME", (long)ST_NODIRATIME)) return -1;
+#endif /* ST_NODIRATIME */
+#ifdef ST_RELATIME
+    if (ins(d, "ST_RELATIME", (long)ST_RELATIME)) return -1;
+#endif /* ST_RELATIME */
+
 #if defined(PYOS_OS2)
     if (insertvalues(d)) return -1;
 #endif
SOURCES/00121-add-Modules-to-build-path.patch
New file
@@ -0,0 +1,13 @@
--- Python-2.7.5/Lib/site.py.orig    2013-05-16 12:47:55.000000000 +0200
+++ Python-2.7.5/Lib/site.py    2013-05-16 12:56:20.089058109 +0200
@@ -529,6 +529,10 @@ def main():
     abs__file__()
     known_paths = removeduppaths()
+    from sysconfig import is_python_build
+    if is_python_build():
+        from _sysconfigdata import build_time_vars
+        sys.path.append(os.path.join(build_time_vars['abs_builddir'], 'Modules'))
     if ENABLE_USER_SITE is None:
         ENABLE_USER_SITE = check_enableusersite()
     known_paths = addusersitepackages(known_paths)
SOURCES/00125-less-verbose-COUNT_ALLOCS.patch
New file
@@ -0,0 +1,20 @@
diff -up Python-2.7/Python/pythonrun.c.less-verbose-COUNT_ALLOCS Python-2.7/Python/pythonrun.c
--- Python-2.7/Python/pythonrun.c.less-verbose-COUNT_ALLOCS    2010-08-17 14:49:33.321913909 -0400
+++ Python-2.7/Python/pythonrun.c    2010-08-17 14:54:48.750910403 -0400
@@ -470,7 +470,15 @@ Py_Finalize(void)
     /* Debugging stuff */
 #ifdef COUNT_ALLOCS
-    dump_counts(stdout);
+    /* This is a downstream Fedora modification.
+       The upstream default with COUNT_ALLOCS is to always dump the counts to
+       stdout on exit.  For our debug builds its useful to have the info from
+       COUNT_ALLOCS available, but the stdout info here gets in the way, so
+       we make it optional, wrapping it in an environment variable (modelled
+       on the other PYTHONDUMP* env variables):
+    */
+    if (Py_GETENV("PYTHONDUMPCOUNTS"))
+        dump_counts(stdout);
 #endif
     PRINT_TOTAL_REFS();
SOURCES/00131-disable-tests-in-test_io.patch
New file
@@ -0,0 +1,11 @@
diff -up Python-2.7.2/Lib/test/test_io.py.disable-tests-in-test_io Python-2.7.2/Lib/test/test_io.py
--- Python-2.7.2/Lib/test/test_io.py.disable-tests-in-test_io    2011-09-01 14:18:45.963304089 -0400
+++ Python-2.7.2/Lib/test/test_io.py    2011-09-01 15:08:53.796098413 -0400
@@ -2669,6 +2669,7 @@ class SignalsTest(unittest.TestCase):
         self.check_interrupted_read_retry(lambda x: x,
                                           mode="r")
+    @unittest.skip('rhbz#732998')
     @unittest.skipUnless(threading, 'Threading required for this test.')
     def check_interrupted_write_retry(self, item, **fdopen_kwargs):
         """Check that a buffered write, when it gets interrupted (either
SOURCES/00132-add-rpmbuild-hooks-to-unittest.patch
New file
@@ -0,0 +1,68 @@
diff -up Python-2.7.2/Lib/unittest/case.py.add-rpmbuild-hooks-to-unittest Python-2.7.2/Lib/unittest/case.py
--- Python-2.7.2/Lib/unittest/case.py.add-rpmbuild-hooks-to-unittest    2011-09-08 14:45:47.677169191 -0400
+++ Python-2.7.2/Lib/unittest/case.py    2011-09-08 16:01:36.287858159 -0400
@@ -1,6 +1,7 @@
 """Test case implementation"""
 import collections
+import os
 import sys
 import functools
 import difflib
@@ -94,6 +95,43 @@ def expectedFailure(func):
     return wrapper
+# Non-standard/downstream-only hooks for handling issues with specific test
+# cases:
+
+def _skipInRpmBuild(reason):
+    """
+    Non-standard/downstream-only decorator for marking a specific unit test
+    to be skipped when run within the %check of an rpmbuild.
+
+    Specifically, this takes effect when WITHIN_PYTHON_RPM_BUILD is set within
+    the environment, and has no effect otherwise.
+    """
+    if 'WITHIN_PYTHON_RPM_BUILD' in os.environ:
+        return skip(reason)
+    else:
+        return _id
+
+def _expectedFailureInRpmBuild(func):
+    """
+    Non-standard/downstream-only decorator for marking a specific unit test
+    as expected to fail within the %check of an rpmbuild.
+
+    Specifically, this takes effect when WITHIN_PYTHON_RPM_BUILD is set within
+    the environment, and has no effect otherwise.
+    """
+    @functools.wraps(func)
+    def wrapper(*args, **kwargs):
+        if 'WITHIN_PYTHON_RPM_BUILD' in os.environ:
+            try:
+                func(*args, **kwargs)
+            except Exception:
+                raise _ExpectedFailure(sys.exc_info())
+            raise _UnexpectedSuccess
+        else:
+            # Call directly:
+            func(*args, **kwargs)
+    return wrapper
+
 class _AssertRaisesContext(object):
     """A context manager used to implement TestCase.assertRaises* methods."""
diff -up Python-2.7.2/Lib/unittest/__init__.py.add-rpmbuild-hooks-to-unittest Python-2.7.2/Lib/unittest/__init__.py
--- Python-2.7.2/Lib/unittest/__init__.py.add-rpmbuild-hooks-to-unittest    2011-09-08 14:59:39.534112310 -0400
+++ Python-2.7.2/Lib/unittest/__init__.py    2011-09-08 15:07:09.191081562 -0400
@@ -57,7 +57,8 @@ __unittest = True
 from .result import TestResult
 from .case import (TestCase, FunctionTestCase, SkipTest, skip, skipIf,
-                   skipUnless, expectedFailure)
+                   skipUnless, expectedFailure,
+                   _skipInRpmBuild, _expectedFailureInRpmBuild)
 from .suite import BaseTestSuite, TestSuite
 from .loader import (TestLoader, defaultTestLoader, makeSuite, getTestCaseNames,
                      findTestCases)
SOURCES/00133-skip-test_dl.patch
New file
@@ -0,0 +1,13 @@
diff -up Python-2.7.2/Lib/test/test_dl.py.skip-test_dl Python-2.7.2/Lib/test/test_dl.py
--- Python-2.7.2/Lib/test/test_dl.py.skip-test_dl    2011-09-08 15:18:40.529034289 -0400
+++ Python-2.7.2/Lib/test/test_dl.py    2011-09-08 16:29:45.184742670 -0400
@@ -13,6 +13,9 @@ sharedlibs = [
     ('/usr/lib/libc.dylib', 'getpid'),
     ]
+# (also, "dl" is deprecated in favor of ctypes)
+@unittest._skipInRpmBuild('fails on 64-bit builds: '
+    'module dl requires sizeof(int) == sizeof(long) == sizeof(char*)')
 def test_main():
     for s, func in sharedlibs:
         try:
SOURCES/00134-fix-COUNT_ALLOCS-failure-in-test_sys.patch
New file
@@ -0,0 +1,14 @@
--- Python-2.7.2/Lib/test/test_sys.py.mark-tests-that-fail-in-rpmbuild    2011-09-08 18:02:31.627362039 -0400
+++ Python-2.7.2/Lib/test/test_sys.py    2011-09-08 18:15:29.450308851 -0400
@@ -734,6 +734,11 @@ class SizeofTest(unittest.TestCase):
         # (PyTypeObject + PyNumberMethods +  PyMappingMethods +
         #  PySequenceMethods + PyBufferProcs)
         s = vsize('P2P15Pl4PP9PP11PI') + struct.calcsize('41P 10P 3P 6P')
+
+        # COUNT_ALLOCS adds further fields to the end of a PyTypeObject:
+        if hasattr(sys, 'getcounts'):
+            s += size('P')
+
         class newstyleclass(object):
             pass
         check(newstyleclass, s)
SOURCES/00135-skip-test-within-test_weakref-in-debug-build.patch
New file
@@ -0,0 +1,18 @@
diff -up Python-2.7.2/Lib/test/test_weakref.py.skip-test-within-test_weakref-in-debug-build Python-2.7.2/Lib/test/test_weakref.py
--- Python-2.7.2/Lib/test/test_weakref.py.skip-test-within-test_weakref-in-debug-build    2011-09-08 17:55:09.675392260 -0400
+++ Python-2.7.2/Lib/test/test_weakref.py    2011-09-08 17:59:08.857375903 -0400
@@ -550,6 +550,14 @@ class ReferencesTestCase(TestBase):
         del c1, c2, C, D
         gc.collect()
+    # In a debug build, this fails with:
+    #   AssertionError: Lists differ: [] != ['C went away']
+    #   Second list contains 1 additional elements.
+    #   First extra element 0:
+    #   C went away
+    #   - []
+    #   + ['C went away']
+    @unittest.skipIf(hasattr(sys, 'getobjects'), 'debug build')
     def test_callback_in_cycle_resurrection(self):
         import gc
SOURCES/00136-skip-tests-of-seeking-stdin-in-rpmbuild.patch
New file
@@ -0,0 +1,22 @@
diff -up Python-2.7.2/Lib/test/test_file2k.py.skip-tests-of-seeking-stdin-in-rpmbuild Python-2.7.2/Lib/test/test_file2k.py
--- Python-2.7.2/Lib/test/test_file2k.py.skip-tests-of-seeking-stdin-in-rpmbuild    2011-09-08 17:23:50.922520729 -0400
+++ Python-2.7.2/Lib/test/test_file2k.py    2011-09-08 17:24:41.368517277 -0400
@@ -213,6 +213,7 @@ class OtherFileTests(unittest.TestCase):
             else:
                 f.close()
+    @unittest._skipInRpmBuild('seems not to raise the exception when run in Koji')
     def testStdin(self):
         # This causes the interpreter to exit on OSF1 v5.1.
         if sys.platform != 'osf1V5':
diff -up Python-2.7.2/Lib/test/test_file.py.skip-tests-of-seeking-stdin-in-rpmbuild Python-2.7.2/Lib/test/test_file.py
--- Python-2.7.2/Lib/test/test_file.py.skip-tests-of-seeking-stdin-in-rpmbuild    2011-09-08 17:20:31.146534389 -0400
+++ Python-2.7.2/Lib/test/test_file.py    2011-09-08 17:24:45.016517030 -0400
@@ -154,6 +154,7 @@ class OtherFileTests(unittest.TestCase):
                 f.close()
                 self.fail('%r is an invalid file mode' % mode)
+    @unittest._skipInRpmBuild('seems not to raise the exception when run in Koji')
     def testStdin(self):
         # This causes the interpreter to exit on OSF1 v5.1.
         if sys.platform != 'osf1V5':
SOURCES/00137-skip-distutils-tests-that-fail-in-rpmbuild.patch
New file
@@ -0,0 +1,12 @@
diff -up Python-2.7.3/Lib/distutils/tests/test_bdist_rpm.py.mark-tests-that-fail-in-rpmbuild Python-2.7.3/Lib/distutils/tests/test_bdist_rpm.py
--- Python-2.7.3/Lib/distutils/tests/test_bdist_rpm.py.mark-tests-that-fail-in-rpmbuild    2012-04-09 19:07:29.000000000 -0400
+++ Python-2.7.3/Lib/distutils/tests/test_bdist_rpm.py    2012-04-13 00:20:08.223819263 -0400
@@ -24,6 +24,7 @@ setup(name='foo', version='0.1', py_modu
 """
+@unittest._skipInRpmBuild("don't try to nest one rpm build inside another rpm build")
 class BuildRpmTestCase(support.TempdirManager,
                        support.LoggingSilencer,
                        unittest.TestCase):
diff -up Python-2.7.3/Lib/distutils/tests/test_build_ext.py.mark-tests-that-fail-in-rpmbuild Python-2.7.3/Lib/distutils/tests/test_build_ext.py
SOURCES/00138-fix-distutils-tests-in-debug-build.patch
New file
@@ -0,0 +1,68 @@
diff -up Python-2.7.2/Lib/distutils/tests/test_build_ext.py.mark-tests-that-fail-in-rpmbuild Python-2.7.2/Lib/distutils/tests/test_build_ext.py
--- Python-2.7.2/Lib/distutils/tests/test_build_ext.py.mark-tests-that-fail-in-rpmbuild    2011-09-08 16:07:25.033834312 -0400
+++ Python-2.7.2/Lib/distutils/tests/test_build_ext.py    2011-09-08 17:43:15.656441082 -0400
@@ -330,6 +332,7 @@ class BuildExtTestCase(support.TempdirMa
         self.assertEqual(lastdir, 'bar')
     def test_ext_fullpath(self):
+        debug_ext = sysconfig.get_config_var("DEBUG_EXT")
         ext = sysconfig.get_config_vars()['SO']
         dist = Distribution()
         cmd = build_ext(dist)
@@ -337,14 +340,14 @@ class BuildExtTestCase(support.TempdirMa
         cmd.distribution.package_dir = {'': 'src'}
         cmd.distribution.packages = ['lxml', 'lxml.html']
         curdir = os.getcwd()
-        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
+        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + debug_ext + ext)
         path = cmd.get_ext_fullpath('lxml.etree')
         self.assertEqual(wanted, path)
         # building lxml.etree not inplace
         cmd.inplace = 0
         cmd.build_lib = os.path.join(curdir, 'tmpdir')
-        wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
+        wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + debug_ext + ext)
         path = cmd.get_ext_fullpath('lxml.etree')
         self.assertEqual(wanted, path)
@@ -354,13 +357,13 @@ class BuildExtTestCase(support.TempdirMa
         cmd.distribution.packages = ['twisted', 'twisted.runner.portmap']
         path = cmd.get_ext_fullpath('twisted.runner.portmap')
         wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
-                              'portmap' + ext)
+                              'portmap' + debug_ext + ext)
         self.assertEqual(wanted, path)
         # building twisted.runner.portmap inplace
         cmd.inplace = 1
         path = cmd.get_ext_fullpath('twisted.runner.portmap')
-        wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
+        wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + debug_ext + ext)
         self.assertEqual(wanted, path)
     def test_build_ext_inplace(self):
@@ -373,8 +376,9 @@ class BuildExtTestCase(support.TempdirMa
         cmd.distribution.package_dir = {'': 'src'}
         cmd.distribution.packages = ['lxml', 'lxml.html']
         curdir = os.getcwd()
+        debug_ext = sysconfig.get_config_var("DEBUG_EXT")
         ext = sysconfig.get_config_var("SO")
-        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
+        wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + debug_ext + ext)
         path = cmd.get_ext_fullpath('lxml.etree')
         self.assertEqual(wanted, path)
@@ -412,10 +416,11 @@ class BuildExtTestCase(support.TempdirMa
         dist = Distribution({'name': 'UpdateManager'})
         cmd = build_ext(dist)
         cmd.ensure_finalized()
+        debug_ext = sysconfig.get_config_var("DEBUG_EXT")
         ext = sysconfig.get_config_var("SO")
         ext_name = os.path.join('UpdateManager', 'fdsend')
         ext_path = cmd.get_ext_fullpath(ext_name)
-        wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + ext)
+        wanted = os.path.join(cmd.build_lib, 'UpdateManager', 'fdsend' + debug_ext + ext)
         self.assertEqual(ext_path, wanted)
     def test_build_ext_path_cross_platform(self):
SOURCES/00139-skip-test_float-known-failure-on-arm.patch
New file
@@ -0,0 +1,11 @@
diff -up Python-2.7.2/Lib/test/test_float.py.skip-test_float-known-failure-on-arm Python-2.7.2/Lib/test/test_float.py
--- Python-2.7.2/Lib/test/test_float.py.skip-test_float-known-failure-on-arm    2011-09-08 19:34:09.000986128 -0400
+++ Python-2.7.2/Lib/test/test_float.py    2011-09-08 19:34:57.969982779 -0400
@@ -1072,6 +1072,7 @@ class HexFloatTestCase(unittest.TestCase
                     self.identical(got, expected)
+    @unittest.skip('Known failure on ARM: http://bugs.python.org/issue8265')
     def test_from_hex(self):
         MIN = self.MIN;
         MAX = self.MAX;
SOURCES/00140-skip-test_ctypes-known-failure-on-sparc.patch
New file
@@ -0,0 +1,11 @@
diff -up Python-2.7.2/Lib/ctypes/test/test_callbacks.py.skip-test_ctypes-known-failure-on-sparc Python-2.7.2/Lib/ctypes/test/test_callbacks.py
--- Python-2.7.2/Lib/ctypes/test/test_callbacks.py.skip-test_ctypes-known-failure-on-sparc    2011-09-08 19:42:35.541951490 -0400
+++ Python-2.7.2/Lib/ctypes/test/test_callbacks.py    2011-09-08 19:43:40.676947036 -0400
@@ -67,6 +67,7 @@ class Callbacks(unittest.TestCase):
         self.check_type(c_longlong, 42)
         self.check_type(c_longlong, -42)
+    @unittest.skip('Known failure on Sparc: http://bugs.python.org/issue8314')
     def test_ulonglong(self):
         # test some 64-bit values, with and without msb set.
         self.check_type(c_ulonglong, 10955412242170339782)
SOURCES/00141-fix-test_gc_with_COUNT_ALLOCS.patch
New file
@@ -0,0 +1,24 @@
diff -up Python-2.7.2/Lib/test/test_gc.py.fix-test_gc_with_COUNT_ALLOCS Python-2.7.2/Lib/test/test_gc.py
--- Python-2.7.2/Lib/test/test_gc.py.fix-test_gc_with_COUNT_ALLOCS    2011-09-08 19:49:13.045924309 -0400
+++ Python-2.7.2/Lib/test/test_gc.py    2011-09-08 19:50:07.035920617 -0400
@@ -102,11 +102,17 @@ class GCTests(unittest.TestCase):
         del a
         self.assertNotEqual(gc.collect(), 0)
         del B, C
-        self.assertNotEqual(gc.collect(), 0)
+        if hasattr(sys, 'getcounts'):
+            self.assertEqual(gc.collect(), 0)
+        else:
+            self.assertNotEqual(gc.collect(), 0)
         A.a = A()
         del A
-        self.assertNotEqual(gc.collect(), 0)
-        self.assertEqual(gc.collect(), 0)
+        if hasattr(sys, 'getcounts'):
+            self.assertEqual(gc.collect(), 0)
+        else:
+            self.assertNotEqual(gc.collect(), 0)
+            self.assertEqual(gc.collect(), 0)
     def test_method(self):
         # Tricky: self.__init__ is a bound method, it references the instance.
SOURCES/00142-skip-failing-pty-tests-in-rpmbuild.patch
New file
@@ -0,0 +1,22 @@
diff -up Python-2.7.2/Lib/test/test_openpty.py.skip-failing-pty-tests-in-rpmbuild Python-2.7.2/Lib/test/test_openpty.py
--- Python-2.7.2/Lib/test/test_openpty.py.skip-failing-pty-tests-in-rpmbuild    2011-09-09 05:09:28.698920379 -0400
+++ Python-2.7.2/Lib/test/test_openpty.py    2011-09-09 05:10:54.805914490 -0400
@@ -8,6 +8,7 @@ if not hasattr(os, "openpty"):
 class OpenptyTest(unittest.TestCase):
+    @unittest._skipInRpmBuild('sometimes fails in Koji, possibly due to a mock issue (rhbz#714627)')
     def test(self):
         master, slave = os.openpty()
         if not os.isatty(slave):
diff -up Python-2.7.2/Lib/test/test_pty.py.skip-failing-pty-tests-in-rpmbuild Python-2.7.2/Lib/test/test_pty.py
--- Python-2.7.2/Lib/test/test_pty.py.skip-failing-pty-tests-in-rpmbuild    2011-09-09 05:09:36.781919825 -0400
+++ Python-2.7.2/Lib/test/test_pty.py    2011-09-09 05:11:14.741913127 -0400
@@ -109,6 +109,7 @@ class PtyTest(unittest.TestCase):
         os.close(master_fd)
+    @unittest._skipInRpmBuild('sometimes fails in Koji, possibly due to a mock issue (rhbz#714627)')
     def test_fork(self):
         debug("calling pty.fork()")
         pid, master_fd = pty.fork()
SOURCES/00143-tsc-on-ppc.patch
New file
@@ -0,0 +1,58 @@
diff -up Python-2.7.2/Python/ceval.c.tsc-on-ppc Python-2.7.2/Python/ceval.c
--- Python-2.7.2/Python/ceval.c.tsc-on-ppc    2011-08-23 14:59:48.051300849 -0400
+++ Python-2.7.2/Python/ceval.c    2011-08-23 15:33:25.412162902 -0400
@@ -37,24 +37,42 @@ typedef unsigned long long uint64;
 */
 #if defined(__ppc__) || defined (__powerpc__)
-#define READ_TIMESTAMP(var) ppc_getcounter(&var)
+#if defined( __powerpc64__) || defined(__LP64__)
+/* 64-bit PowerPC */
+#define READ_TIMESTAMP(var) ppc64_getcounter(&var)
+static void
+ppc64_getcounter(uint64 *v)
+{
+    /* On 64-bit PowerPC we can read the 64-bit timebase directly into a
+       64-bit register */
+    uint64 timebase;
+#ifdef _ARCH_PWR4
+    asm volatile ("mfspr %0,268" : "=r" (timebase));
+#else
+    asm volatile ("mftb %0" : "=r" (timebase));
+#endif
+    *v = timebase;
+}
+
+#else
+/* 32-bit PowerPC */
+#define READ_TIMESTAMP(var) ppc32_getcounter(&var)
 static void
-ppc_getcounter(uint64 *v)
+ppc32_getcounter(uint64 *v)
 {
-    register unsigned long tbu, tb, tbu2;
+    union { long long ll; long ii[2]; } u;
+    long tmp;
   loop:
-    asm volatile ("mftbu %0" : "=r" (tbu) );
-    asm volatile ("mftb  %0" : "=r" (tb)  );
-    asm volatile ("mftbu %0" : "=r" (tbu2));
-    if (__builtin_expect(tbu != tbu2, 0)) goto loop;
-
-    /* The slightly peculiar way of writing the next lines is
-       compiled better by GCC than any other way I tried. */
-    ((long*)(v))[0] = tbu;
-    ((long*)(v))[1] = tb;
+    asm volatile ("mftbu %0" : "=r" (u.ii[0]) );
+    asm volatile ("mftb  %0" : "=r" (u.ii[1]) );
+    asm volatile ("mftbu %0" : "=r" (tmp));
+    if (__builtin_expect(u.ii[0] != tmp, 0)) goto loop;
+
+    *v = u.ll;
 }
+#endif /* powerpc 32/64 bit */
 #elif defined(__i386__)
SOURCES/00144-no-gdbm.patch
New file
@@ -0,0 +1,12 @@
diff -up Python-2.7.2/Modules/Setup.dist.no-gdbm Python-2.7.2/Modules/Setup.dist
--- Python-2.7.2/Modules/Setup.dist.no-gdbm    2011-09-13 14:25:43.496095926 -0400
+++ Python-2.7.2/Modules/Setup.dist    2011-09-13 14:25:46.491095724 -0400
@@ -396,7 +396,7 @@ dl dlmodule.c
 #
 # First, look at Setup.config; configure may have set this for you.
-gdbm gdbmmodule.c -lgdbm
+# gdbm gdbmmodule.c -lgdbm
 # Sleepycat Berkeley DB interface.
SOURCES/00146-hashlib-fips.patch
New file
@@ -0,0 +1,729 @@
diff -up Python-2.7.2/Lib/hashlib.py.hashlib-fips Python-2.7.2/Lib/hashlib.py
--- Python-2.7.2/Lib/hashlib.py.hashlib-fips    2011-06-11 11:46:24.000000000 -0400
+++ Python-2.7.2/Lib/hashlib.py    2011-09-14 00:21:26.194252001 -0400
@@ -6,9 +6,12 @@
 __doc__ = """hashlib module - A common interface to many hash functions.
-new(name, string='') - returns a new hash object implementing the
-                       given hash function; initializing the hash
-                       using the given string data.
+new(name, string='', usedforsecurity=True)
+     - returns a new hash object implementing the given hash function;
+       initializing the hash using the given string data.
+
+       "usedforsecurity" is a non-standard extension for better supporting
+       FIPS-compliant environments (see below)
 Named constructor functions are also available, these are much faster
 than using new():
@@ -24,6 +27,20 @@ the zlib module.
 Choose your hash function wisely.  Some have known collision weaknesses.
 sha384 and sha512 will be slow on 32 bit platforms.
+Our implementation of hashlib uses OpenSSL.
+
+OpenSSL has a "FIPS mode", which, if enabled, may restrict the available hashes
+to only those that are compliant with FIPS regulations.  For example, it may
+deny the use of MD5, on the grounds that this is not secure for uses such as
+authentication, system integrity checking, or digital signatures.
+
+If you need to use such a hash for non-security purposes (such as indexing into
+a data structure for speed), you can override the keyword argument
+"usedforsecurity" from True to False to signify that your code is not relying
+on the hash for security purposes, and this will allow the hash to be usable
+even in FIPS mode.  This is not a standard feature of Python 2.7's hashlib, and
+is included here to better support FIPS mode.
+
 Hash objects have these methods:
  - update(arg): Update the hash object with the string arg. Repeated calls
                 are equivalent to a single call with the concatenation of all
@@ -63,74 +80,39 @@ algorithms = __always_supported
 __all__ = __always_supported + ('new', 'algorithms')
-def __get_builtin_constructor(name):
-    try:
-        if name in ('SHA1', 'sha1'):
-            import _sha
-            return _sha.new
-        elif name in ('MD5', 'md5'):
-            import _md5
-            return _md5.new
-        elif name in ('SHA256', 'sha256', 'SHA224', 'sha224'):
-            import _sha256
-            bs = name[3:]
-            if bs == '256':
-                return _sha256.sha256
-            elif bs == '224':
-                return _sha256.sha224
-        elif name in ('SHA512', 'sha512', 'SHA384', 'sha384'):
-            import _sha512
-            bs = name[3:]
-            if bs == '512':
-                return _sha512.sha512
-            elif bs == '384':
-                return _sha512.sha384
-    except ImportError:
-        pass  # no extension module, this hash is unsupported.
-
-    raise ValueError('unsupported hash type ' + name)
-
-
 def __get_openssl_constructor(name):
     try:
         f = getattr(_hashlib, 'openssl_' + name)
         # Allow the C module to raise ValueError.  The function will be
         # defined but the hash not actually available thanks to OpenSSL.
-        f()
+        #
+        # We pass "usedforsecurity=False" to disable FIPS-based restrictions:
+        # at this stage we're merely seeing if the function is callable,
+        # rather than using it for actual work.
+        f(usedforsecurity=False)
         # Use the C function directly (very fast)
         return f
     except (AttributeError, ValueError):
-        return __get_builtin_constructor(name)
+        raise
-
-def __py_new(name, string=''):
-    """new(name, string='') - Return a new hashing object using the named algorithm;
-    optionally initialized with a string.
-    """
-    return __get_builtin_constructor(name)(string)
-
-
-def __hash_new(name, string=''):
+def __hash_new(name, string='', usedforsecurity=True):
     """new(name, string='') - Return a new hashing object using the named algorithm;
     optionally initialized with a string.
+    Override 'usedforsecurity' to False when using for non-security purposes in
+    a FIPS environment
     """
     try:
-        return _hashlib.new(name, string)
+        return _hashlib.new(name, string, usedforsecurity)
     except ValueError:
-        # If the _hashlib module (OpenSSL) doesn't support the named
-        # hash, try using our builtin implementations.
-        # This allows for SHA224/256 and SHA384/512 support even though
-        # the OpenSSL library prior to 0.9.8 doesn't provide them.
-        return __get_builtin_constructor(name)(string)
-
+        raise
 try:
     import _hashlib
     new = __hash_new
     __get_hash = __get_openssl_constructor
 except ImportError:
-    new = __py_new
-    __get_hash = __get_builtin_constructor
+    # We don't build the legacy modules
+    raise
 for __func_name in __always_supported:
     # try them all, some may not work due to the OpenSSL
@@ -143,4 +125,4 @@ for __func_name in __always_supported:
 # Cleanup locals()
 del __always_supported, __func_name, __get_hash
-del __py_new, __hash_new, __get_openssl_constructor
+del __hash_new, __get_openssl_constructor
diff -up Python-2.7.2/Lib/test/test_hashlib.py.hashlib-fips Python-2.7.2/Lib/test/test_hashlib.py
--- Python-2.7.2/Lib/test/test_hashlib.py.hashlib-fips    2011-06-11 11:46:25.000000000 -0400
+++ Python-2.7.2/Lib/test/test_hashlib.py    2011-09-14 01:08:55.525254195 -0400
@@ -32,6 +32,19 @@ def hexstr(s):
         r = r + h[(i >> 4) & 0xF] + h[i & 0xF]
     return r
+def openssl_enforces_fips():
+    # Use the "openssl" command (if present) to try to determine if the local
+    # OpenSSL is configured to enforce FIPS
+    from subprocess import Popen, PIPE
+    try:
+        p = Popen(['openssl', 'md5'],
+                  stdin=PIPE, stdout=PIPE, stderr=PIPE)
+    except OSError:
+        # "openssl" command not found
+        return False
+    stdout, stderr = p.communicate(input=b'abc')
+    return b'unknown cipher' in stderr
+OPENSSL_ENFORCES_FIPS = openssl_enforces_fips()
 class HashLibTestCase(unittest.TestCase):
     supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1',
@@ -61,10 +74,10 @@ class HashLibTestCase(unittest.TestCase)
         # of hashlib.new given the algorithm name.
         for algorithm, constructors in self.constructors_to_test.items():
             constructors.add(getattr(hashlib, algorithm))
-            def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm):
+            def _test_algorithm_via_hashlib_new(data=None, _alg=algorithm, usedforsecurity=True):
                 if data is None:
-                    return hashlib.new(_alg)
-                return hashlib.new(_alg, data)
+                    return hashlib.new(_alg, usedforsecurity=usedforsecurity)
+                return hashlib.new(_alg, data, usedforsecurity=usedforsecurity)
             constructors.add(_test_algorithm_via_hashlib_new)
         _hashlib = self._conditional_import_module('_hashlib')
@@ -78,28 +91,13 @@ class HashLibTestCase(unittest.TestCase)
                 if constructor:
                     constructors.add(constructor)
-        _md5 = self._conditional_import_module('_md5')
-        if _md5:
-            self.constructors_to_test['md5'].add(_md5.new)
-        _sha = self._conditional_import_module('_sha')
-        if _sha:
-            self.constructors_to_test['sha1'].add(_sha.new)
-        _sha256 = self._conditional_import_module('_sha256')
-        if _sha256:
-            self.constructors_to_test['sha224'].add(_sha256.sha224)
-            self.constructors_to_test['sha256'].add(_sha256.sha256)
-        _sha512 = self._conditional_import_module('_sha512')
-        if _sha512:
-            self.constructors_to_test['sha384'].add(_sha512.sha384)
-            self.constructors_to_test['sha512'].add(_sha512.sha512)
-
         super(HashLibTestCase, self).__init__(*args, **kwargs)
     def test_hash_array(self):
         a = array.array("b", range(10))
         constructors = self.constructors_to_test.itervalues()
         for cons in itertools.chain.from_iterable(constructors):
-            c = cons(a)
+            c = cons(a, usedforsecurity=False)
             c.hexdigest()
     def test_algorithms_attribute(self):
@@ -115,28 +113,9 @@ class HashLibTestCase(unittest.TestCase)
         self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam')
         self.assertRaises(TypeError, hashlib.new, 1)
-    def test_get_builtin_constructor(self):
-        get_builtin_constructor = hashlib.__dict__[
-                '__get_builtin_constructor']
-        self.assertRaises(ValueError, get_builtin_constructor, 'test')
-        try:
-            import _md5
-        except ImportError:
-            pass
-        # This forces an ImportError for "import _md5" statements
-        sys.modules['_md5'] = None
-        try:
-            self.assertRaises(ValueError, get_builtin_constructor, 'md5')
-        finally:
-            if '_md5' in locals():
-                sys.modules['_md5'] = _md5
-            else:
-                del sys.modules['_md5']
-        self.assertRaises(TypeError, get_builtin_constructor, 3)
-
     def test_hexdigest(self):
         for name in self.supported_hash_names:
-            h = hashlib.new(name)
+            h = hashlib.new(name, usedforsecurity=False)
             self.assertTrue(hexstr(h.digest()) == h.hexdigest())
     def test_large_update(self):
@@ -145,16 +125,16 @@ class HashLibTestCase(unittest.TestCase)
         abcs = aas + bees + cees
         for name in self.supported_hash_names:
-            m1 = hashlib.new(name)
+            m1 = hashlib.new(name, usedforsecurity=False)
             m1.update(aas)
             m1.update(bees)
             m1.update(cees)
-            m2 = hashlib.new(name)
+            m2 = hashlib.new(name, usedforsecurity=False)
             m2.update(abcs)
             self.assertEqual(m1.digest(), m2.digest(), name+' update problem.')
-            m3 = hashlib.new(name, abcs)
+            m3 = hashlib.new(name, abcs, usedforsecurity=False)
             self.assertEqual(m1.digest(), m3.digest(), name+' new problem.')
     def check(self, name, data, digest):
@@ -162,7 +142,7 @@ class HashLibTestCase(unittest.TestCase)
         # 2 is for hashlib.name(...) and hashlib.new(name, ...)
         self.assertGreaterEqual(len(constructors), 2)
         for hash_object_constructor in constructors:
-            computed = hash_object_constructor(data).hexdigest()
+            computed = hash_object_constructor(data, usedforsecurity=False).hexdigest()
             self.assertEqual(
                     computed, digest,
                     "Hash algorithm %s constructed using %s returned hexdigest"
@@ -172,7 +152,8 @@ class HashLibTestCase(unittest.TestCase)
     def check_unicode(self, algorithm_name):
         # Unicode objects are not allowed as input.
-        expected = hashlib.new(algorithm_name, str(u'spam')).hexdigest()
+        expected = hashlib.new(algorithm_name, str(u'spam'),
+                               usedforsecurity=False).hexdigest()
         self.check(algorithm_name, u'spam', expected)
     def test_unicode(self):
@@ -354,6 +335,70 @@ class HashLibTestCase(unittest.TestCase)
         self.assertEqual(expected_hash, hasher.hexdigest())
+    def test_issue9146(self):
+        # Ensure that various ways to use "MD5" from "hashlib" don't segfault:
+        m = hashlib.md5(usedforsecurity=False)
+        m.update(b'abc\n')
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+        m = hashlib.new('md5', usedforsecurity=False)
+        m.update(b'abc\n')
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+        m = hashlib.md5(b'abc\n', usedforsecurity=False)
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+        m = hashlib.new('md5', b'abc\n', usedforsecurity=False)
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+    def assertRaisesUnknownCipher(self, callable_obj=None, *args, **kwargs):
+        try:
+            callable_obj(*args, **kwargs)
+        except ValueError, e:
+            if not e.args[0].endswith('unknown cipher'):
+                self.fail('Incorrect exception raised')
+        else:
+            self.fail('Exception was not raised')
+
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
+                         'FIPS enforcement required for this test.')
+    def test_hashlib_fips_mode(self):
+        # Ensure that we raise a ValueError on vanilla attempts to use MD5
+        # in hashlib in a FIPS-enforced setting:
+        self.assertRaisesUnknownCipher(hashlib.md5)
+        self.assertRaisesUnknownCipher(hashlib.new, 'md5')
+
+    @unittest.skipUnless(OPENSSL_ENFORCES_FIPS,
+                         'FIPS enforcement required for this test.')
+    def test_hashopenssl_fips_mode(self):
+        # Verify the _hashlib module's handling of md5:
+        import _hashlib
+
+        assert hasattr(_hashlib, 'openssl_md5')
+
+        # Ensure that _hashlib raises a ValueError on vanilla attempts to
+        # use MD5 in a FIPS-enforced setting:
+        self.assertRaisesUnknownCipher(_hashlib.openssl_md5)
+        self.assertRaisesUnknownCipher(_hashlib.new, 'md5')
+
+        # Ensure that in such a setting we can whitelist a callsite with
+        # usedforsecurity=False and have it succeed:
+        m = _hashlib.openssl_md5(usedforsecurity=False)
+        m.update('abc\n')
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+        m = _hashlib.new('md5', usedforsecurity=False)
+        m.update('abc\n')
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+        m = _hashlib.openssl_md5('abc\n', usedforsecurity=False)
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+        m = _hashlib.new('md5', 'abc\n', usedforsecurity=False)
+        self.assertEquals(m.hexdigest(), "0bee89b07a248e27c83fc3d5951213c1")
+
+
+
 def test_main():
     test_support.run_unittest(HashLibTestCase)
diff -up Python-2.7.2/Modules/_hashopenssl.c.hashlib-fips Python-2.7.2/Modules/_hashopenssl.c
--- Python-2.7.2/Modules/_hashopenssl.c.hashlib-fips    2011-06-11 11:46:26.000000000 -0400
+++ Python-2.7.2/Modules/_hashopenssl.c    2011-09-14 00:21:26.199252001 -0400
@@ -36,6 +36,8 @@
 #endif
 /* EVP is the preferred interface to hashing in OpenSSL */
+#include <openssl/ssl.h>
+#include <openssl/err.h>
 #include <openssl/evp.h>
 #define MUNCH_SIZE INT_MAX
@@ -65,11 +67,19 @@ typedef struct {
 static PyTypeObject EVPtype;
+/* Struct to hold all the cached information we need on a specific algorithm.
+   We have one of these per algorithm */
+typedef struct {
+    PyObject *name_obj;
+    EVP_MD_CTX ctxs[2];
+    /* ctx_ptrs will point to ctxs unless an error occurred, when it will
+       be NULL: */
+    EVP_MD_CTX *ctx_ptrs[2];
+    PyObject *error_msgs[2];
+} EVPCachedInfo;
-#define DEFINE_CONSTS_FOR_NEW(Name)  \
-    static PyObject *CONST_ ## Name ## _name_obj = NULL; \
-    static EVP_MD_CTX CONST_new_ ## Name ## _ctx; \
-    static EVP_MD_CTX *CONST_new_ ## Name ## _ctx_p = NULL;
+#define DEFINE_CONSTS_FOR_NEW(Name) \
+    static EVPCachedInfo cached_info_ ##Name;
 DEFINE_CONSTS_FOR_NEW(md5)
 DEFINE_CONSTS_FOR_NEW(sha1)
@@ -115,6 +125,48 @@ EVP_hash(EVPobject *self, const void *vp
     }
 }
+static void
+mc_ctx_init(EVP_MD_CTX *ctx, int usedforsecurity)
+{
+    EVP_MD_CTX_init(ctx);
+
+    /*
+      If the user has declared that this digest is being used in a
+      non-security role (e.g. indexing into a data structure), set
+      the exception flag for openssl to allow it
+    */
+    if (!usedforsecurity) {
+#ifdef EVP_MD_CTX_FLAG_NON_FIPS_ALLOW
+        EVP_MD_CTX_set_flags(ctx,
+                             EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
+#endif
+    }
+}
+
+/* Get an error msg for the last error as a PyObject */
+static PyObject *
+error_msg_for_last_error(void)
+{
+    char *errstr;
+
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
+    ERR_clear_error();
+
+    return PyString_FromString(errstr); /* Can be NULL */
+}
+
+static void
+set_evp_exception(void)
+{
+    char *errstr;
+
+    errstr = ERR_error_string(ERR_peek_last_error(), NULL);
+    ERR_clear_error();
+
+    PyErr_SetString(PyExc_ValueError, errstr);
+}
+
+
 /* Internal methods for a hash object */
 static void
@@ -313,14 +365,15 @@ EVP_repr(PyObject *self)
 static int
 EVP_tp_init(EVPobject *self, PyObject *args, PyObject *kwds)
 {
-    static char *kwlist[] = {"name", "string", NULL};
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
     PyObject *name_obj = NULL;
+    int usedforsecurity = 1;
     Py_buffer view = { 0 };
     char *nameStr;
     const EVP_MD *digest;
-    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s*:HASH", kwlist,
-                                     &name_obj, &view)) {
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s*i:HASH", kwlist,
+                                     &name_obj, &view, &usedforsecurity)) {
         return -1;
     }
@@ -336,7 +389,12 @@ EVP_tp_init(EVPobject *self, PyObject *a
         PyBuffer_Release(&view);
         return -1;
     }
-    EVP_DigestInit(&self->ctx, digest);
+    mc_ctx_init(&self->ctx, usedforsecurity);
+    if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
+        set_evp_exception();
+        PyBuffer_Release(&view);
+        return -1;
+    }
     self->name = name_obj;
     Py_INCREF(self->name);
@@ -420,7 +478,8 @@ static PyTypeObject EVPtype = {
 static PyObject *
 EVPnew(PyObject *name_obj,
        const EVP_MD *digest, const EVP_MD_CTX *initial_ctx,
-       const unsigned char *cp, Py_ssize_t len)
+       const unsigned char *cp, Py_ssize_t len,
+       int usedforsecurity)
 {
     EVPobject *self;
@@ -435,7 +494,12 @@ EVPnew(PyObject *name_obj,
     if (initial_ctx) {
         EVP_MD_CTX_copy(&self->ctx, initial_ctx);
     } else {
-        EVP_DigestInit(&self->ctx, digest);
+        mc_ctx_init(&self->ctx, usedforsecurity);
+        if (!EVP_DigestInit_ex(&self->ctx, digest, NULL)) {
+            set_evp_exception();
+            Py_DECREF(self);
+            return NULL;
+        }
     }
     if (cp && len) {
@@ -459,20 +523,28 @@ PyDoc_STRVAR(EVP_new__doc__,
 An optional string argument may be provided and will be\n\
 automatically hashed.\n\
 \n\
-The MD5 and SHA1 algorithms are always supported.\n");
+The MD5 and SHA1 algorithms are always supported.\n\
+\n\
+An optional \"usedforsecurity=True\" keyword argument is provided for use in\n\
+environments that enforce FIPS-based restrictions.  Some implementations of\n\
+OpenSSL can be configured to prevent the usage of non-secure algorithms (such\n\
+as MD5).  If you have a non-security use for these algorithms (e.g. a hash\n\
+table), you can override this argument by marking the callsite as\n\
+\"usedforsecurity=False\".");
 static PyObject *
 EVP_new(PyObject *self, PyObject *args, PyObject *kwdict)
 {
-    static char *kwlist[] = {"name", "string", NULL};
+    static char *kwlist[] = {"name", "string", "usedforsecurity", NULL};
     PyObject *name_obj = NULL;
     Py_buffer view = { 0 };
     PyObject *ret_obj;
     char *name;
     const EVP_MD *digest;
+    int usedforsecurity = 1;
-    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*:new", kwlist,
-                                     &name_obj, &view)) {
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, "O|s*i:new", kwlist,
+                                     &name_obj, &view, &usedforsecurity)) {
         return NULL;
     }
@@ -484,58 +556,118 @@ EVP_new(PyObject *self, PyObject *args,
     digest = EVP_get_digestbyname(name);
     ret_obj = EVPnew(name_obj, digest, NULL, (unsigned char*)view.buf,
-                     view.len);
+                     view.len, usedforsecurity);
     PyBuffer_Release(&view);
     return ret_obj;
 }
 /*
- *  This macro generates constructor function definitions for specific
- *  hash algorithms.  These constructors are much faster than calling
- *  the generic one passing it a python string and are noticably
- *  faster than calling a python new() wrapper.  Thats important for
+ *  This macro and function generates a family of constructor function
+ *  definitions for specific hash algorithms.  These constructors are much
+ *  faster than calling the generic one passing it a python string and are
+ *  noticably faster than calling a python new() wrapper.  That's important for
  *  code that wants to make hashes of a bunch of small strings.
  */
 #define GEN_CONSTRUCTOR(NAME)  \
     static PyObject * \
-    EVP_new_ ## NAME (PyObject *self, PyObject *args) \
+    EVP_new_ ## NAME (PyObject *self, PyObject *args, PyObject *kwdict)  \
     { \
-        Py_buffer view = { 0 }; \
-        PyObject *ret_obj; \
-     \
-        if (!PyArg_ParseTuple(args, "|s*:" #NAME , &view)) { \
-            return NULL; \
-        } \
-     \
-        ret_obj = EVPnew( \
-                    CONST_ ## NAME ## _name_obj, \
-                    NULL, \
-                    CONST_new_ ## NAME ## _ctx_p, \
-                    (unsigned char*)view.buf, view.len); \
-        PyBuffer_Release(&view); \
-        return ret_obj; \
+        return implement_specific_EVP_new(self, args, kwdict,      \
+                                          "|s*i:" #NAME,           \
+                                          &cached_info_ ## NAME ); \
     }
+static PyObject *
+implement_specific_EVP_new(PyObject *self, PyObject *args, PyObject *kwdict,
+                           const char *format,
+                           EVPCachedInfo *cached_info)
+{
+    static char *kwlist[] = {"string", "usedforsecurity", NULL};
+    Py_buffer view = { 0 };
+    int usedforsecurity = 1;
+    int idx;
+    PyObject *ret_obj = NULL;
+
+    assert(cached_info);
+
+    if (!PyArg_ParseTupleAndKeywords(args, kwdict, format, kwlist,
+                                     &view, &usedforsecurity)) {
+        return NULL;
+    }
+
+    idx = usedforsecurity ? 1 : 0;
+
+    /*
+     * If an error occurred during creation of the global content, the ctx_ptr
+     * will be NULL, and the error_msg will hopefully be non-NULL:
+     */
+    if (cached_info->ctx_ptrs[idx]) {
+        /* We successfully initialized this context; copy it: */
+        ret_obj = EVPnew(cached_info->name_obj,
+                         NULL,
+                         cached_info->ctx_ptrs[idx],
+                         (unsigned char*)view.buf, view.len,
+                         usedforsecurity);
+    } else {
+        /* Some kind of error happened initializing the global context for
+           this (digest, usedforsecurity) pair.
+           Raise an exception with the saved error message: */
+        if (cached_info->error_msgs[idx]) {
+            PyErr_SetObject(PyExc_ValueError, cached_info->error_msgs[idx]);
+        } else {
+            PyErr_SetString(PyExc_ValueError, "Error initializing hash");
+        }
+    }
+
+    PyBuffer_Release(&view);
+
+    return ret_obj;
+}
+
 /* a PyMethodDef structure for the constructor */
 #define CONSTRUCTOR_METH_DEF(NAME)  \
-    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, METH_VARARGS, \
+    {"openssl_" #NAME, (PyCFunction)EVP_new_ ## NAME, \
+        METH_VARARGS |METH_KEYWORDS, \
         PyDoc_STR("Returns a " #NAME \
                   " hash object; optionally initialized with a string") \
     }
-/* used in the init function to setup a constructor: initialize OpenSSL
-   constructor constants if they haven't been initialized already.  */
-#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do { \
-    if (CONST_ ## NAME ## _name_obj == NULL) { \
-    CONST_ ## NAME ## _name_obj = PyString_FromString(#NAME); \
-        if (EVP_get_digestbyname(#NAME)) { \
-            CONST_new_ ## NAME ## _ctx_p = &CONST_new_ ## NAME ## _ctx; \
-            EVP_DigestInit(CONST_new_ ## NAME ## _ctx_p, EVP_get_digestbyname(#NAME)); \
-        } \
-    } \
+/*
+  Macro/function pair to set up the constructors.
+
+  Try to initialize a context for each hash twice, once with
+  EVP_MD_CTX_FLAG_NON_FIPS_ALLOW and once without.
+
+  Any that have errors during initialization will end up wit a NULL ctx_ptrs
+  entry, and err_msgs will be set (unless we're very low on memory)
+*/
+#define INIT_CONSTRUCTOR_CONSTANTS(NAME)  do {    \
+    init_constructor_constant(&cached_info_ ## NAME, #NAME); \
 } while (0);
+static void
+init_constructor_constant(EVPCachedInfo *cached_info, const char *name)
+{
+    assert(cached_info);
+    cached_info->name_obj = PyString_FromString(name);
+    if (EVP_get_digestbyname(name)) {
+        int i;
+        for (i=0; i<2; i++) {
+            mc_ctx_init(&cached_info->ctxs[i], i);
+            if (EVP_DigestInit_ex(&cached_info->ctxs[i],
+                                  EVP_get_digestbyname(name), NULL)) {
+                /* Success: */
+                cached_info->ctx_ptrs[i] = &cached_info->ctxs[i];
+            } else {
+                /* Failure: */
+                cached_info->ctx_ptrs[i] = NULL;
+                cached_info->error_msgs[i] = error_msg_for_last_error();
+            }
+        }
+    }
+}
+
 GEN_CONSTRUCTOR(md5)
 GEN_CONSTRUCTOR(sha1)
 #ifdef _OPENSSL_SUPPORTS_SHA2
@@ -565,13 +700,10 @@ init_hashlib(void)
 {
     PyObject *m;
+    SSL_load_error_strings();
+    SSL_library_init();
     OpenSSL_add_all_digests();
-    /* TODO build EVP_functions openssl_* entries dynamically based
-     * on what hashes are supported rather than listing many
-     * but having some be unsupported.  Only init appropriate
-     * constants. */
-
     Py_TYPE(&EVPtype) = &PyType_Type;
     if (PyType_Ready(&EVPtype) < 0)
         return;
diff -up Python-2.7.2/Modules/Setup.dist.hashlib-fips Python-2.7.2/Modules/Setup.dist
--- Python-2.7.2/Modules/Setup.dist.hashlib-fips    2011-09-14 00:21:26.163252001 -0400
+++ Python-2.7.2/Modules/Setup.dist    2011-09-14 00:21:26.201252001 -0400
@@ -248,14 +248,14 @@ imageop imageop.c    # Operations on images
 # 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 algorithms.
 # (NIST's Secure Hash Algorithms.)
-_sha shamodule.c
-_sha256 sha256module.c
-_sha512 sha512module.c
+#_sha shamodule.c
+#_sha256 sha256module.c
+#_sha512 sha512module.c
 # SGI IRIX specific modules -- off by default.
diff -up Python-2.7.2/setup.py.hashlib-fips Python-2.7.2/setup.py
--- Python-2.7.2/setup.py.hashlib-fips    2011-09-14 00:21:25.722252001 -0400
+++ Python-2.7.2/setup.py    2011-09-14 00:21:26.203252001 -0400
@@ -768,21 +768,6 @@ class PyBuildExt(build_ext):
                 print ("warning: openssl 0x%08x is too old for _hashlib" %
                        openssl_ver)
                 missing.append('_hashlib')
-        if COMPILED_WITH_PYDEBUG or not have_usable_openssl:
-            # The _sha module implements the SHA1 hash algorithm.
-            exts.append( Extension('_sha', ['shamodule.c']) )
-            # 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.
-            exts.append( Extension('_md5',
-                            sources = ['md5module.c', 'md5.c'],
-                            depends = ['md5.h']) )
-
-        min_sha2_openssl_ver = 0x00908000
-        if COMPILED_WITH_PYDEBUG or openssl_ver < min_sha2_openssl_ver:
-            # OpenSSL doesn't do these until 0.9.8 so we'll bring our own hash
-            exts.append( Extension('_sha256', ['sha256module.c']) )
-            exts.append( Extension('_sha512', ['sha512module.c']) )
         # Modules that provide persistent dictionary-like semantics.  You will
         # probably want to arrange for at least one of them to be available on
SOURCES/00147-add-debug-malloc-stats.patch
New file
@@ -0,0 +1,711 @@
diff -up Python-2.7.2/Include/dictobject.h.add-debug-malloc-stats Python-2.7.2/Include/dictobject.h
--- Python-2.7.2/Include/dictobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/dictobject.h    2011-09-16 19:03:25.105821625 -0400
@@ -150,6 +150,8 @@ PyAPI_FUNC(PyObject *) PyDict_GetItemStr
 PyAPI_FUNC(int) PyDict_SetItemString(PyObject *dp, const char *key, PyObject *item);
 PyAPI_FUNC(int) PyDict_DelItemString(PyObject *dp, const char *key);
+PyAPI_FUNC(void) _PyDict_DebugMallocStats(FILE *out);
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Include/floatobject.h.add-debug-malloc-stats Python-2.7.2/Include/floatobject.h
--- Python-2.7.2/Include/floatobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/floatobject.h    2011-09-16 19:03:25.106821625 -0400
@@ -132,6 +132,7 @@ PyAPI_FUNC(PyObject *) _PyFloat_FormatAd
    failure.  Used in builtin_round in bltinmodule.c. */
 PyAPI_FUNC(PyObject *) _Py_double_round(double x, int ndigits);
+PyAPI_FUNC(void) _PyFloat_DebugMallocStats(FILE* out);
 #ifdef __cplusplus
diff -up Python-2.7.2/Include/frameobject.h.add-debug-malloc-stats Python-2.7.2/Include/frameobject.h
--- Python-2.7.2/Include/frameobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/frameobject.h    2011-09-16 19:03:25.107821625 -0400
@@ -80,6 +80,8 @@ PyAPI_FUNC(void) PyFrame_FastToLocals(Py
 PyAPI_FUNC(int) PyFrame_ClearFreeList(void);
+PyAPI_FUNC(void) _PyFrame_DebugMallocStats(FILE *out);
+
 /* Return the line of code the frame is currently executing. */
 PyAPI_FUNC(int) PyFrame_GetLineNumber(PyFrameObject *);
diff -up Python-2.7.2/Include/intobject.h.add-debug-malloc-stats Python-2.7.2/Include/intobject.h
--- Python-2.7.2/Include/intobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/intobject.h    2011-09-16 19:03:25.107821625 -0400
@@ -74,6 +74,8 @@ PyAPI_FUNC(PyObject *) _PyInt_FormatAdva
                          char *format_spec,
                          Py_ssize_t format_spec_len);
+PyAPI_FUNC(void) _PyInt_DebugMallocStats(FILE *out);
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Include/listobject.h.add-debug-malloc-stats Python-2.7.2/Include/listobject.h
--- Python-2.7.2/Include/listobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/listobject.h    2011-09-16 19:03:25.107821625 -0400
@@ -62,6 +62,8 @@ PyAPI_FUNC(PyObject *) _PyList_Extend(Py
 #define PyList_SET_ITEM(op, i, v) (((PyListObject *)(op))->ob_item[i] = (v))
 #define PyList_GET_SIZE(op)    Py_SIZE(op)
+PyAPI_FUNC(void) _PyList_DebugMallocStats(FILE *out);
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Include/methodobject.h.add-debug-malloc-stats Python-2.7.2/Include/methodobject.h
--- Python-2.7.2/Include/methodobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/methodobject.h    2011-09-16 19:03:25.108821625 -0400
@@ -87,6 +87,10 @@ typedef struct {
 PyAPI_FUNC(int) PyCFunction_ClearFreeList(void);
+PyAPI_FUNC(void) _PyCFunction_DebugMallocStats(FILE *out);
+PyAPI_FUNC(void) _PyMethod_DebugMallocStats(FILE *out);
+
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Include/object.h.add-debug-malloc-stats Python-2.7.2/Include/object.h
--- Python-2.7.2/Include/object.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/object.h    2011-09-16 19:03:25.108821625 -0400
@@ -980,6 +980,13 @@ PyAPI_DATA(PyObject *) _PyTrash_delete_l
             _PyTrash_thread_deposit_object((PyObject*)op); \
     } while (0);
+PyAPI_FUNC(void)
+_PyDebugAllocatorStats(FILE *out, const char *block_name, int num_blocks,
+               size_t sizeof_block);
+
+PyAPI_FUNC(void)
+_PyObject_DebugTypeStats(FILE *out);
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Include/objimpl.h.add-debug-malloc-stats Python-2.7.2/Include/objimpl.h
--- Python-2.7.2/Include/objimpl.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/objimpl.h    2011-09-16 19:03:25.108821625 -0400
@@ -101,13 +101,13 @@ PyAPI_FUNC(void) PyObject_Free(void *);
 /* Macros */
 #ifdef WITH_PYMALLOC
+PyAPI_FUNC(void) _PyObject_DebugMallocStats(FILE *out);
 #ifdef PYMALLOC_DEBUG   /* WITH_PYMALLOC && PYMALLOC_DEBUG */
 PyAPI_FUNC(void *) _PyObject_DebugMalloc(size_t nbytes);
 PyAPI_FUNC(void *) _PyObject_DebugRealloc(void *p, size_t nbytes);
 PyAPI_FUNC(void) _PyObject_DebugFree(void *p);
 PyAPI_FUNC(void) _PyObject_DebugDumpAddress(const void *p);
 PyAPI_FUNC(void) _PyObject_DebugCheckAddress(const void *p);
-PyAPI_FUNC(void) _PyObject_DebugMallocStats(void);
 PyAPI_FUNC(void *) _PyObject_DebugMallocApi(char api, size_t nbytes);
 PyAPI_FUNC(void *) _PyObject_DebugReallocApi(char api, void *p, size_t nbytes);
 PyAPI_FUNC(void) _PyObject_DebugFreeApi(char api, void *p);
diff -up Python-2.7.2/Include/stringobject.h.add-debug-malloc-stats Python-2.7.2/Include/stringobject.h
--- Python-2.7.2/Include/stringobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/stringobject.h    2011-09-16 19:03:25.109821625 -0400
@@ -204,6 +204,8 @@ PyAPI_FUNC(PyObject *) _PyBytes_FormatAd
                            char *format_spec,
                            Py_ssize_t format_spec_len);
+PyAPI_FUNC(void) _PyString_DebugMallocStats(FILE *out);
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Include/unicodeobject.h.add-debug-malloc-stats Python-2.7.2/Include/unicodeobject.h
--- Python-2.7.2/Include/unicodeobject.h.add-debug-malloc-stats    2011-06-11 11:46:23.000000000 -0400
+++ Python-2.7.2/Include/unicodeobject.h    2011-09-16 19:03:25.109821625 -0400
@@ -1406,6 +1406,8 @@ PyAPI_FUNC(int) _PyUnicode_IsAlpha(
     Py_UNICODE ch       /* Unicode character */
     );
+PyAPI_FUNC(void) _PyUnicode_DebugMallocStats(FILE *out);
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Lib/test/test_sys.py.add-debug-malloc-stats Python-2.7.2/Lib/test/test_sys.py
--- Python-2.7.2/Lib/test/test_sys.py.add-debug-malloc-stats    2011-09-16 19:03:25.048821626 -0400
+++ Python-2.7.2/Lib/test/test_sys.py    2011-09-16 19:03:25.110821625 -0400
@@ -473,6 +473,32 @@ class SysModuleTest(unittest.TestCase):
         p.wait()
         self.assertIn(executable, ["''", repr(sys.executable)])
+    def test_debugmallocstats(self):
+        # Test sys._debugmallocstats()
+
+        import subprocess
+
+        # Verify the default of writing to stderr:
+        p = subprocess.Popen([sys.executable,
+                              '-c', 'import sys; sys._debugmallocstats()'],
+                             stderr=subprocess.PIPE)
+        out, err = p.communicate()
+        p.wait()
+        self.assertIn("arenas allocated current", err)
+
+        # Verify that we can redirect the output to a file (not a file-like
+        # object, though):
+        with open('mallocstats.txt', 'w') as out:
+            sys._debugmallocstats(out)
+        result = open('mallocstats.txt').read()
+        self.assertIn("arenas allocated current", result)
+        os.unlink('mallocstats.txt')
+
+        # Verify that the destination must be a file:
+        with self.assertRaises(TypeError):
+            sys._debugmallocstats(42)
+
+
 class SizeofTest(unittest.TestCase):
     def setUp(self):
diff -up Python-2.7.2/Objects/classobject.c.add-debug-malloc-stats Python-2.7.2/Objects/classobject.c
--- Python-2.7.2/Objects/classobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/classobject.c    2011-09-16 19:03:25.110821625 -0400
@@ -2670,3 +2670,12 @@ PyMethod_Fini(void)
 {
     (void)PyMethod_ClearFreeList();
 }
+
+/* Print summary info about the state of the optimized allocator */
+void
+_PyMethod_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out,
+                           "free PyMethodObject",
+                           numfree, sizeof(PyMethodObject));
+}
diff -up Python-2.7.2/Objects/dictobject.c.add-debug-malloc-stats Python-2.7.2/Objects/dictobject.c
--- Python-2.7.2/Objects/dictobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/dictobject.c    2011-09-16 19:03:25.111821625 -0400
@@ -225,6 +225,15 @@ show_track(void)
 static PyDictObject *free_list[PyDict_MAXFREELIST];
 static int numfree = 0;
+/* Print summary info about the state of the optimized allocator */
+void
+_PyDict_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out,
+                           "free PyDictObject", numfree, sizeof(PyDictObject));
+}
+
+
 void
 PyDict_Fini(void)
 {
diff -up Python-2.7.2/Objects/floatobject.c.add-debug-malloc-stats Python-2.7.2/Objects/floatobject.c
--- Python-2.7.2/Objects/floatobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/floatobject.c    2011-09-16 19:03:25.111821625 -0400
@@ -35,6 +35,22 @@ typedef struct _floatblock PyFloatBlock;
 static PyFloatBlock *block_list = NULL;
 static PyFloatObject *free_list = NULL;
+/* Print summary info about the state of the optimized allocator */
+void
+_PyFloat_DebugMallocStats(FILE *out)
+{
+  int num_blocks = 0;
+  PyFloatBlock *block;
+
+  /* Walk the block list, counting */
+  for (block = block_list; block ; block = block->next) {
+      num_blocks++;
+  }
+
+  _PyDebugAllocatorStats(out,
+                         "PyFloatBlock", num_blocks, sizeof(PyFloatBlock));
+}
+
 static PyFloatObject *
 fill_free_list(void)
 {
diff -up Python-2.7.2/Objects/frameobject.c.add-debug-malloc-stats Python-2.7.2/Objects/frameobject.c
--- Python-2.7.2/Objects/frameobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/frameobject.c    2011-09-16 19:03:25.112821625 -0400
@@ -980,3 +980,13 @@ PyFrame_Fini(void)
     Py_XDECREF(builtin_object);
     builtin_object = NULL;
 }
+
+/* Print summary info about the state of the optimized allocator */
+void
+_PyFrame_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out,
+                           "free PyFrameObject",
+                           numfree, sizeof(PyFrameObject));
+}
+
diff -up Python-2.7.2/Objects/intobject.c.add-debug-malloc-stats Python-2.7.2/Objects/intobject.c
--- Python-2.7.2/Objects/intobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/intobject.c    2011-09-16 19:03:25.112821625 -0400
@@ -44,6 +44,23 @@ typedef struct _intblock PyIntBlock;
 static PyIntBlock *block_list = NULL;
 static PyIntObject *free_list = NULL;
+
+/* Print summary info about the state of the optimized allocator */
+void
+_PyInt_DebugMallocStats(FILE *out)
+{
+    int num_blocks = 0;
+    PyIntBlock *block;
+
+    /* Walk the block list, counting */
+    for (block = block_list; block ; block = block->next) {
+        num_blocks++;
+    }
+
+    _PyDebugAllocatorStats(out,
+                           "PyIntBlock", num_blocks, sizeof(PyIntBlock));
+}
+
 static PyIntObject *
 fill_free_list(void)
 {
diff -up Python-2.7.2/Objects/listobject.c.add-debug-malloc-stats Python-2.7.2/Objects/listobject.c
--- Python-2.7.2/Objects/listobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/listobject.c    2011-09-16 19:03:25.113821625 -0400
@@ -109,6 +109,15 @@ PyList_Fini(void)
     }
 }
+/* Print summary info about the state of the optimized allocator */
+void
+_PyList_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out,
+                           "free PyListObject",
+                           numfree, sizeof(PyListObject));
+}
+
 PyObject *
 PyList_New(Py_ssize_t size)
 {
diff -up Python-2.7.2/Objects/methodobject.c.add-debug-malloc-stats Python-2.7.2/Objects/methodobject.c
--- Python-2.7.2/Objects/methodobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/methodobject.c    2011-09-16 19:03:25.113821625 -0400
@@ -412,6 +412,15 @@ PyCFunction_Fini(void)
     (void)PyCFunction_ClearFreeList();
 }
+/* Print summary info about the state of the optimized allocator */
+void
+_PyCFunction_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out,
+                           "free PyCFunction",
+                           numfree, sizeof(PyCFunction));
+}
+
 /* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(),
    but it's part of the API so we need to keep a function around that
    existing C extensions can call.
diff -up Python-2.7.2/Objects/object.c.add-debug-malloc-stats Python-2.7.2/Objects/object.c
--- Python-2.7.2/Objects/object.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/object.c    2011-09-16 19:04:46.463820849 -0400
@@ -2334,6 +2334,23 @@ PyMem_Free(void *p)
     PyMem_FREE(p);
 }
+void
+_PyObject_DebugTypeStats(FILE *out)
+{
+    _PyString_DebugMallocStats(out);
+    _PyCFunction_DebugMallocStats(out);
+    _PyDict_DebugMallocStats(out);
+    _PyFloat_DebugMallocStats(out);
+    _PyFrame_DebugMallocStats(out);
+    _PyInt_DebugMallocStats(out);
+    _PyList_DebugMallocStats(out);
+    _PyMethod_DebugMallocStats(out);
+    _PySet_DebugMallocStats(out);
+    _PyTuple_DebugMallocStats(out);
+#if Py_USING_UNICODE
+    _PyUnicode_DebugMallocStats(out);
+#endif
+}
 /* These methods are used to control infinite recursion in repr, str, print,
    etc.  Container objects that may recursively contain themselves,
diff -up Python-2.7.2/Objects/obmalloc.c.add-debug-malloc-stats Python-2.7.2/Objects/obmalloc.c
--- Python-2.7.2/Objects/obmalloc.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/obmalloc.c    2011-09-16 19:03:25.114821625 -0400
@@ -508,12 +508,10 @@ static struct arena_object* usable_arena
 /* Number of arenas allocated that haven't been free()'d. */
 static size_t narenas_currently_allocated = 0;
-#ifdef PYMALLOC_DEBUG
 /* Total number of times malloc() called to allocate an arena. */
 static size_t ntimes_arena_allocated = 0;
 /* High water mark (max value ever seen) for narenas_currently_allocated. */
 static size_t narenas_highwater = 0;
-#endif
 /* Allocate a new arena.  If we run out of memory, return NULL.  Else
  * allocate a new arena, and return the address of an arena_object
@@ -528,7 +526,7 @@ new_arena(void)
 #ifdef PYMALLOC_DEBUG
     if (Py_GETENV("PYTHONMALLOCSTATS"))
-        _PyObject_DebugMallocStats();
+        _PyObject_DebugMallocStats(stderr);
 #endif
     if (unused_arena_objects == NULL) {
         uint i;
@@ -588,11 +586,9 @@ new_arena(void)
     }
     ++narenas_currently_allocated;
-#ifdef PYMALLOC_DEBUG
     ++ntimes_arena_allocated;
     if (narenas_currently_allocated > narenas_highwater)
         narenas_highwater = narenas_currently_allocated;
-#endif
     arenaobj->freepools = NULL;
     /* pool_address <- first pool-aligned address in the arena
        nfreepools <- number of whole pools that fit after alignment */
@@ -1694,17 +1690,19 @@ _PyObject_DebugDumpAddress(const void *p
     }
 }
+#endif  /* PYMALLOC_DEBUG */
+
 static size_t
-printone(const char* msg, size_t value)
+printone(FILE *out, const char* msg, size_t value)
 {
     int i, k;
     char buf[100];
     size_t origvalue = value;
-    fputs(msg, stderr);
+    fputs(msg, out);
     for (i = (int)strlen(msg); i < 35; ++i)
-        fputc(' ', stderr);
-    fputc('=', stderr);
+        fputc(' ', out);
+    fputc('=', out);
     /* Write the value with commas. */
     i = 22;
@@ -1725,17 +1723,32 @@ printone(const char* msg, size_t value)
     while (i >= 0)
         buf[i--] = ' ';
-    fputs(buf, stderr);
+    fputs(buf, out);
     return origvalue;
 }
-/* Print summary info to stderr about the state of pymalloc's structures.
+void
+_PyDebugAllocatorStats(FILE *out,
+                       const char *block_name, int num_blocks, size_t sizeof_block)
+{
+       char buf1[128];
+       char buf2[128];
+       PyOS_snprintf(buf1, sizeof(buf1),
+                     "%d %ss * %zd bytes each",
+                     num_blocks, block_name, sizeof_block);
+       PyOS_snprintf(buf2, sizeof(buf2),
+                     "%48s ", buf1);
+      (void)printone(out, buf2, num_blocks * sizeof_block);
+}
+
+
+/* Print summary info to "out" about the state of pymalloc's structures.
  * In Py_DEBUG mode, also perform some expensive internal consistency
  * checks.
  */
 void
-_PyObject_DebugMallocStats(void)
+_PyObject_DebugMallocStats(FILE *out)
 {
     uint i;
     const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
@@ -1764,7 +1777,7 @@ _PyObject_DebugMallocStats(void)
     size_t total;
     char buf[128];
-    fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
+    fprintf(out, "Small block threshold = %d, in %u size classes.\n",
             SMALL_REQUEST_THRESHOLD, numclasses);
     for (i = 0; i < numclasses; ++i)
@@ -1818,10 +1831,10 @@ _PyObject_DebugMallocStats(void)
     }
     assert(narenas == narenas_currently_allocated);
-    fputc('\n', stderr);
+    fputc('\n', out);
     fputs("class   size   num pools   blocks in use  avail blocks\n"
           "-----   ----   ---------   -------------  ------------\n",
-          stderr);
+          out);
     for (i = 0; i < numclasses; ++i) {
         size_t p = numpools[i];
@@ -1832,7 +1845,7 @@ _PyObject_DebugMallocStats(void)
             assert(b == 0 && f == 0);
             continue;
         }
-        fprintf(stderr, "%5u %6u "
+        fprintf(out, "%5u %6u "
                         "%11" PY_FORMAT_SIZE_T "u "
                         "%15" PY_FORMAT_SIZE_T "u "
                         "%13" PY_FORMAT_SIZE_T "u\n",
@@ -1842,36 +1855,35 @@ _PyObject_DebugMallocStats(void)
         pool_header_bytes += p * POOL_OVERHEAD;
         quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
     }
-    fputc('\n', stderr);
-    (void)printone("# times object malloc called", serialno);
-
-    (void)printone("# arenas allocated total", ntimes_arena_allocated);
-    (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
-    (void)printone("# arenas highwater mark", narenas_highwater);
-    (void)printone("# arenas allocated current", narenas);
+    fputc('\n', out);
+#ifdef PYMALLOC_DEBUG
+    (void)printone(out, "# times object malloc called", serialno);
+#endif
+    (void)printone(out, "# arenas allocated total", ntimes_arena_allocated);
+    (void)printone(out, "# arenas reclaimed", ntimes_arena_allocated - narenas);
+    (void)printone(out, "# arenas highwater mark", narenas_highwater);
+    (void)printone(out, "# arenas allocated current", narenas);
     PyOS_snprintf(buf, sizeof(buf),
         "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
         narenas, ARENA_SIZE);
-    (void)printone(buf, narenas * ARENA_SIZE);
+    (void)printone(out, buf, narenas * ARENA_SIZE);
-    fputc('\n', stderr);
+    fputc('\n', out);
-    total = printone("# bytes in allocated blocks", allocated_bytes);
-    total += printone("# bytes in available blocks", available_bytes);
+    total = printone(out, "# bytes in allocated blocks", allocated_bytes);
+    total += printone(out, "# bytes in available blocks", available_bytes);
     PyOS_snprintf(buf, sizeof(buf),
         "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
-    total += printone(buf, (size_t)numfreepools * POOL_SIZE);
+    total += printone(out, buf, (size_t)numfreepools * POOL_SIZE);
-    total += printone("# bytes lost to pool headers", pool_header_bytes);
-    total += printone("# bytes lost to quantization", quantization);
-    total += printone("# bytes lost to arena alignment", arena_alignment);
-    (void)printone("Total", total);
+    total += printone(out, "# bytes lost to pool headers", pool_header_bytes);
+    total += printone(out, "# bytes lost to quantization", quantization);
+    total += printone(out, "# bytes lost to arena alignment", arena_alignment);
+    (void)printone(out, "Total", total);
 }
-#endif  /* PYMALLOC_DEBUG */
-
 #ifdef Py_USING_MEMORY_DEBUGGER
 /* Make this function last so gcc won't inline it since the definition is
  * after the reference.
diff -up Python-2.7.2/Objects/setobject.c.add-debug-malloc-stats Python-2.7.2/Objects/setobject.c
--- Python-2.7.2/Objects/setobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/setobject.c    2011-09-16 19:03:25.115821625 -0400
@@ -1088,6 +1088,16 @@ PySet_Fini(void)
     Py_CLEAR(emptyfrozenset);
 }
+/* Print summary info about the state of the optimized allocator */
+void
+_PySet_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out,
+                           "free PySetObject",
+                           numfree, sizeof(PySetObject));
+}
+
+
 static PyObject *
 set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
 {
diff -up Python-2.7.2/Objects/stringobject.c.add-debug-malloc-stats Python-2.7.2/Objects/stringobject.c
--- Python-2.7.2/Objects/stringobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/stringobject.c    2011-09-16 19:03:25.116821625 -0400
@@ -4822,3 +4822,43 @@ void _Py_ReleaseInternedStrings(void)
     PyDict_Clear(interned);
     Py_CLEAR(interned);
 }
+
+void _PyString_DebugMallocStats(FILE *out)
+{
+    ssize_t i;
+    int num_immortal = 0, num_mortal = 0;
+    ssize_t immortal_size = 0, mortal_size = 0;
+
+    if (interned == NULL || !PyDict_Check(interned))
+        return;
+
+    for (i = 0; i <= ((PyDictObject*)interned)->ma_mask; i++) {
+        PyDictEntry *ep = ((PyDictObject*)interned)->ma_table + i;
+        PyObject *pvalue = ep->me_value;
+        if (pvalue != NULL) {
+            PyStringObject *s = (PyStringObject *)ep->me_key;
+
+            switch (s->ob_sstate) {
+            case SSTATE_NOT_INTERNED:
+                /* XXX Shouldn't happen */
+                break;
+            case SSTATE_INTERNED_IMMORTAL:
+                num_immortal ++;
+                immortal_size += s->ob_size;
+                break;
+            case SSTATE_INTERNED_MORTAL:
+                num_mortal ++;
+                mortal_size += s->ob_size;
+                break;
+            default:
+                Py_FatalError("Inconsistent interned string state.");
+            }
+        }
+    }
+
+    fprintf(out, "%d mortal interned strings\n", num_mortal);
+    fprintf(out, "%d immortal interned strings\n", num_immortal);
+    fprintf(out, "total size of all interned strings: "
+            "%zi/%zi "
+            "mortal/immortal\n", mortal_size, immortal_size);
+}
diff -up Python-2.7.2/Objects/tupleobject.c.add-debug-malloc-stats Python-2.7.2/Objects/tupleobject.c
--- Python-2.7.2/Objects/tupleobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/tupleobject.c    2011-09-16 19:03:25.116821625 -0400
@@ -44,6 +44,22 @@ show_track(void)
 }
 #endif
+/* Print summary info about the state of the optimized allocator */
+void
+_PyTuple_DebugMallocStats(FILE *out)
+{
+#if PyTuple_MAXSAVESIZE > 0
+    int i;
+    char buf[128];
+    for (i = 1; i < PyTuple_MAXSAVESIZE; i++) {
+        PyOS_snprintf(buf, sizeof(buf),
+                      "free %d-sized PyTupleObject", i);
+        _PyDebugAllocatorStats(out,
+                               buf,
+                               numfree[i], _PyObject_VAR_SIZE(&PyTuple_Type, i));
+    }
+#endif
+}
 PyObject *
 PyTuple_New(register Py_ssize_t size)
diff -up Python-2.7.2/Objects/unicodeobject.c.add-debug-malloc-stats Python-2.7.2/Objects/unicodeobject.c
--- Python-2.7.2/Objects/unicodeobject.c.add-debug-malloc-stats    2011-06-11 11:46:27.000000000 -0400
+++ Python-2.7.2/Objects/unicodeobject.c    2011-09-16 19:03:25.118821625 -0400
@@ -8883,6 +8883,12 @@ _PyUnicode_Fini(void)
     (void)PyUnicode_ClearFreeList();
 }
+void _PyUnicode_DebugMallocStats(FILE *out)
+{
+    _PyDebugAllocatorStats(out, "free PyUnicodeObject", numfree,
+                           sizeof(PyUnicodeObject));
+}
+
 #ifdef __cplusplus
 }
 #endif
diff -up Python-2.7.2/Python/pythonrun.c.add-debug-malloc-stats Python-2.7.2/Python/pythonrun.c
--- Python-2.7.2/Python/pythonrun.c.add-debug-malloc-stats    2011-09-16 19:03:25.025821626 -0400
+++ Python-2.7.2/Python/pythonrun.c    2011-09-16 19:03:25.118821625 -0400
@@ -549,7 +549,7 @@ Py_Finalize(void)
 #endif /* Py_TRACE_REFS */
 #ifdef PYMALLOC_DEBUG
     if (Py_GETENV("PYTHONMALLOCSTATS"))
-        _PyObject_DebugMallocStats();
+        _PyObject_DebugMallocStats(stderr);
 #endif
     call_ll_exitfuncs();
diff -up Python-2.7.2/Python/sysmodule.c.add-debug-malloc-stats Python-2.7.2/Python/sysmodule.c
--- Python-2.7.2/Python/sysmodule.c.add-debug-malloc-stats    2011-09-16 19:03:25.007821626 -0400
+++ Python-2.7.2/Python/sysmodule.c    2011-09-16 19:03:25.119821625 -0400
@@ -872,6 +872,57 @@ a 11-tuple where the entries in the tupl
 extern "C" {
 #endif
+static PyObject *
+sys_debugmallocstats(PyObject *self, PyObject *args)
+{
+    PyObject *file = NULL;
+    FILE *fp;
+
+    if (!PyArg_ParseTuple(args, "|O!",
+                          &PyFile_Type, &file)) {
+      return NULL;
+    }
+    if (!file) {
+        /* Default to sys.stderr: */
+      file = PySys_GetObject("stderr");
+      if (!file) {
+          PyErr_SetString(PyExc_ValueError, "sys.stderr not set");
+          return NULL;
+      }
+      if (!PyFile_Check(file)) {
+          PyErr_SetString(PyExc_TypeError, "sys.stderr is not a file");
+          return NULL;
+      }
+    }
+
+    Py_INCREF(file);
+    /* OK, we now own a ref on non-NULL "file" */
+
+    fp = PyFile_AsFile(file);
+    if (!fp) {
+        PyErr_SetString(PyExc_ValueError, "file is closed");
+        Py_DECREF(file);
+        return NULL;
+    }
+
+    _PyObject_DebugMallocStats(fp);
+    fputc('\n', fp);
+    _PyObject_DebugTypeStats(fp);
+
+    Py_DECREF(file);
+
+    Py_RETURN_NONE;
+}
+PyDoc_STRVAR(debugmallocstats_doc,
+"_debugmallocstats([file])\n\
+\n\
+Print summary info to the given file (or sys.stderr) about the state of\n\
+pymalloc's structures.\n\
+\n\
+In Py_DEBUG mode, also perform some expensive internal consistency\n\
+checks.\n\
+");
+
 #ifdef Py_TRACE_REFS
 /* Defined in objects.c because it uses static globals if that file */
 extern PyObject *_Py_GetObjects(PyObject *, PyObject *);
@@ -970,6 +1021,8 @@ static PyMethodDef sys_methods[] = {
     {"settrace",        sys_settrace, METH_O, settrace_doc},
     {"gettrace",        sys_gettrace, METH_NOARGS, gettrace_doc},
     {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
+    {"_debugmallocstats", sys_debugmallocstats, METH_VARARGS,
+     debugmallocstats_doc},
     {NULL,              NULL}           /* sentinel */
 };
SOURCES/00153-fix-test_gdb-noise.patch
New file
@@ -0,0 +1,31 @@
--- Lib/test/test_gdb.py.old    2012-04-11 21:04:01.367073855 -0400
+++ Lib/test/test_gdb.py    2012-04-12 08:52:58.320288761 -0400
@@ -96,6 +96,15 @@ class DebuggerTests(unittest.TestCase):
         # Generate a list of commands in gdb's language:
         commands = ['set breakpoint pending yes',
                     'break %s' % breakpoint,
+
+                    # GDB as of Fedora 17 onwards can distinguish between the
+                    # value of a variable at entry vs current value:
+                    #   http://sourceware.org/gdb/onlinedocs/gdb/Variables.html
+                    # which leads to the selftests failing with errors like this:
+                    #   AssertionError: 'v@entry=()' != '()'
+                    # Disable this:
+                    'set print entry-values no',
+
                     'run']
         if cmds_after_breakpoint:
             commands += cmds_after_breakpoint
--- Lib/test/test_gdb.py.old    2012-04-11 21:04:01.367073855 -0400
+++ Lib/test/test_gdb.py    2012-04-12 08:52:58.320288761 -0400
@@ -144,6 +153,10 @@
             'Do you need "set solib-search-path" or '
             '"set sysroot"?',
             )
+        ignore_patterns += ('warning: Unable to open',
+                            'Missing separate debuginfo for',
+                            'Try: yum --disablerepo=',
+                            'Undefined set print command')
         for line in errlines:
             if not line.startswith(ignore_patterns):
                 unexpected_errlines.append(line)
SOURCES/00155-avoid-ctypes-thunks.patch
New file
@@ -0,0 +1,15 @@
diff -up Python-2.7.3/Lib/ctypes/__init__.py.rhbz814391 Python-2.7.3/Lib/ctypes/__init__.py
--- Python-2.7.3/Lib/ctypes/__init__.py.rhbz814391    2012-04-20 14:51:19.390990244 -0400
+++ Python-2.7.3/Lib/ctypes/__init__.py    2012-04-20 14:51:45.141668316 -0400
@@ -272,11 +272,6 @@ def _reset_cache():
     # _SimpleCData.c_char_p_from_param
     POINTER(c_char).from_param = c_char_p.from_param
     _pointer_type_cache[None] = c_void_p
-    # XXX for whatever reasons, creating the first instance of a callback
-    # function is needed for the unittests on Win64 to succeed.  This MAY
-    # be a compiler bug, since the problem occurs only when _ctypes is
-    # compiled with the MS SDK compiler.  Or an uninitialized variable?
-    CFUNCTYPE(c_int)(lambda: None)
 try:
     from _ctypes import set_conversion_mode
SOURCES/00156-gdb-autoload-safepath.patch
New file
@@ -0,0 +1,52 @@
diff -up Python-2.7.3/Lib/test/test_gdb.py.gdb-autoload-safepath Python-2.7.3/Lib/test/test_gdb.py
--- Python-2.7.3/Lib/test/test_gdb.py.gdb-autoload-safepath    2012-04-30 15:53:57.254045220 -0400
+++ Python-2.7.3/Lib/test/test_gdb.py    2012-04-30 16:19:19.569941124 -0400
@@ -54,6 +54,19 @@ def gdb_has_frame_select():
 HAS_PYUP_PYDOWN = gdb_has_frame_select()
+def gdb_has_autoload_safepath():
+    # Recent GDBs will only auto-load scripts from certain safe
+    # locations, so we will need to turn off this protection.
+    # However, if the GDB doesn't have it, then the following
+    # command will generate noise on stderr (rhbz#817072):
+    cmd = "--eval-command=set auto-load safe-path /"
+    p = subprocess.Popen(["gdb", "--batch", cmd],
+                         stderr=subprocess.PIPE)
+    _, stderr = p.communicate()
+    return '"on" or "off" expected.' not in stderr
+
+HAS_AUTOLOAD_SAFEPATH = gdb_has_autoload_safepath()
+
 class DebuggerTests(unittest.TestCase):
     """Test that the debugger can debug Python."""
@@ -112,15 +125,28 @@ class DebuggerTests(unittest.TestCase):
                     'set print entry-values no',
                     'run']
+
+        if HAS_AUTOLOAD_SAFEPATH:
+            # Recent GDBs will only auto-load scripts from certain safe
+            # locations.
+            # Where necessary, turn off this protection to ensure that
+            # our -gdb.py script can be loaded - but not on earlier gdb builds
+            # as this would generate noise on stderr (rhbz#817072):
+            init_commands = ['set auto-load safe-path /']
+        else:
+            init_commands = []
+
         if cmds_after_breakpoint:
             commands += cmds_after_breakpoint
         else:
             commands += ['backtrace']
+        # print init_commands
         # print commands
         # Use "commands" to generate the arguments with which to invoke "gdb":
         args = ["gdb", "--batch"]
+        args += ['--init-eval-command=%s' % cmd for cmd in init_commands]
         args += ['--eval-command=%s' % cmd for cmd in commands]
         args += ["--args",
                  sys.executable]
SOURCES/00157-uid-gid-overflows.patch
New file
@@ -0,0 +1,49 @@
diff -up Python-2.7.3/Lib/test/test_os.py.uid-gid-overflows Python-2.7.3/Lib/test/test_os.py
--- Python-2.7.3/Lib/test/test_os.py.uid-gid-overflows    2012-04-09 19:07:32.000000000 -0400
+++ Python-2.7.3/Lib/test/test_os.py    2012-06-26 14:51:36.000817929 -0400
@@ -677,30 +677,36 @@ if sys.platform != 'win32':
             def test_setuid(self):
                 if os.getuid() != 0:
                     self.assertRaises(os.error, os.setuid, 0)
+                self.assertRaises(TypeError, os.setuid, 'not an int')
                 self.assertRaises(OverflowError, os.setuid, 1<<32)
         if hasattr(os, 'setgid'):
             def test_setgid(self):
                 if os.getuid() != 0:
                     self.assertRaises(os.error, os.setgid, 0)
+                self.assertRaises(TypeError, os.setgid, 'not an int')
                 self.assertRaises(OverflowError, os.setgid, 1<<32)
         if hasattr(os, 'seteuid'):
             def test_seteuid(self):
                 if os.getuid() != 0:
                     self.assertRaises(os.error, os.seteuid, 0)
+                self.assertRaises(TypeError, os.seteuid, 'not an int')
                 self.assertRaises(OverflowError, os.seteuid, 1<<32)
         if hasattr(os, 'setegid'):
             def test_setegid(self):
                 if os.getuid() != 0:
                     self.assertRaises(os.error, os.setegid, 0)
+                self.assertRaises(TypeError, os.setegid, 'not an int')
                 self.assertRaises(OverflowError, os.setegid, 1<<32)
         if hasattr(os, 'setreuid'):
             def test_setreuid(self):
                 if os.getuid() != 0:
                     self.assertRaises(os.error, os.setreuid, 0, 0)
+                self.assertRaises(TypeError, os.setreuid, 'not an int', 0)
+                self.assertRaises(TypeError, os.setreuid, 0, 'not an int')
                 self.assertRaises(OverflowError, os.setreuid, 1<<32, 0)
                 self.assertRaises(OverflowError, os.setreuid, 0, 1<<32)
@@ -715,6 +721,8 @@ if sys.platform != 'win32':
             def test_setregid(self):
                 if os.getuid() != 0:
                     self.assertRaises(os.error, os.setregid, 0, 0)
+                self.assertRaises(TypeError, os.setregid, 'not an int', 0)
+                self.assertRaises(TypeError, os.setregid, 0, 'not an int')
                 self.assertRaises(OverflowError, os.setregid, 1<<32, 0)
                 self.assertRaises(OverflowError, os.setregid, 0, 1<<32)
SOURCES/00165-crypt-module-salt-backport.patch
New file
@@ -0,0 +1,285 @@
diff -up Python-2.7.3/Doc/library/crypt.rst.crypt-module-salt-backport Python-2.7.3/Doc/library/crypt.rst
--- Python-2.7.3/Doc/library/crypt.rst.crypt-module-salt-backport    2012-04-09 19:07:28.000000000 -0400
+++ Python-2.7.3/Doc/library/crypt.rst    2013-02-19 16:44:20.465334062 -0500
@@ -16,9 +16,9 @@
 This module implements an interface to the :manpage:`crypt(3)` routine, which is
 a one-way hash function based upon a modified DES algorithm; see the Unix man
-page for further details.  Possible uses include allowing Python scripts to
-accept typed passwords from the user, or attempting to crack Unix passwords with
-a dictionary.
+page for further details.  Possible uses include storing hashed passwords
+so you can check passwords without storing the actual password, or attempting
+to crack Unix passwords with a dictionary.
 .. index:: single: crypt(3)
@@ -27,15 +27,81 @@ the :manpage:`crypt(3)` routine in the r
 extensions available on the current implementation will also  be available on
 this module.
+Hashing Methods
+---------------
-.. function:: crypt(word, salt)
+The :mod:`crypt` module defines the list of hashing methods (not all methods
+are available on all platforms):
+
+.. data:: METHOD_SHA512
+
+   A Modular Crypt Format method with 16 character salt and 86 character
+   hash.  This is the strongest method.
+
+.. versionadded:: 3.3
+
+.. data:: METHOD_SHA256
+
+   Another Modular Crypt Format method with 16 character salt and 43
+   character hash.
+
+.. versionadded:: 3.3
+
+.. data:: METHOD_MD5
+
+   Another Modular Crypt Format method with 8 character salt and 22
+   character hash.
+
+.. versionadded:: 3.3
+
+.. data:: METHOD_CRYPT
+
+   The traditional method with a 2 character salt and 13 characters of
+   hash.  This is the weakest method.
+
+.. versionadded:: 3.3
+
+
+Module Attributes
+-----------------
+
+
+.. attribute:: methods
+
+   A list of available password hashing algorithms, as
+   ``crypt.METHOD_*`` objects.  This list is sorted from strongest to
+   weakest, and is guaranteed to have at least ``crypt.METHOD_CRYPT``.
+
+.. versionadded:: 3.3
+
+
+Module Functions
+----------------
+
+The :mod:`crypt` module defines the following functions:
+
+.. function:: crypt(word, salt=None)
    *word* will usually be a user's password as typed at a prompt or  in a graphical
-   interface.  *salt* is usually a random two-character string which will be used
-   to perturb the DES algorithm in one of 4096 ways.  The characters in *salt* must
-   be in the set ``[./a-zA-Z0-9]``.  Returns the hashed password as a string, which
-   will be composed of characters from the same alphabet as the salt (the first two
-   characters represent the salt itself).
+   interface.  The optional *salt* is either a string as returned from
+   :func:`mksalt`, one of the ``crypt.METHOD_*`` values (though not all
+   may be available on all platforms), or a full encrypted password
+   including salt, as returned by this function.  If *salt* is not
+   provided, the strongest method will be used (as returned by
+   :func:`methods`.
+
+   Checking a password is usually done by passing the plain-text password
+   as *word* and the full results of a previous :func:`crypt` call,
+   which should be the same as the results of this call.
+
+   *salt* (either a random 2 or 16 character string, possibly prefixed with
+   ``$digit$`` to indicate the method) which will be used to perturb the
+   encryption algorithm.  The characters in *salt* must be in the set
+   ``[./a-zA-Z0-9]``, with the exception of Modular Crypt Format which
+   prefixes a ``$digit$``.
+
+   Returns the hashed password as a string, which will be composed of
+   characters from the same alphabet as the salt.
    .. index:: single: crypt(3)
@@ -43,6 +109,27 @@ this module.
    different sizes in the *salt*, it is recommended to use  the full crypted
    password as salt when checking for a password.
+.. versionchanged:: 3.3
+   Before version 3.3, *salt*  must be specified as a string and cannot
+   accept ``crypt.METHOD_*`` values (which don't exist anyway).
+
+
+.. function:: mksalt(method=None)
+
+   Return a randomly generated salt of the specified method.  If no
+   *method* is given, the strongest method available as returned by
+   :func:`methods` is used.
+
+   The return value is a string either of 2 characters in length for
+   ``crypt.METHOD_CRYPT``, or 19 characters starting with ``$digit$`` and
+   16 random characters from the set ``[./a-zA-Z0-9]``, suitable for
+   passing as the *salt* argument to :func:`crypt`.
+
+.. versionadded:: 3.3
+
+Examples
+--------
+
 A simple example illustrating typical use::
    import crypt, getpass, pwd
@@ -59,3 +146,11 @@ A simple example illustrating typical us
        else:
            return 1
+To generate a hash of a password using the strongest available method and
+check it against the original::
+
+   import crypt
+
+   hashed = crypt.crypt(plaintext)
+   if hashed != crypt.crypt(plaintext, hashed):
+      raise "Hashed version doesn't validate against original"
diff -up Python-2.7.3/Lib/crypt.py.crypt-module-salt-backport Python-2.7.3/Lib/crypt.py
--- Python-2.7.3/Lib/crypt.py.crypt-module-salt-backport    2013-02-19 16:44:20.465334062 -0500
+++ Python-2.7.3/Lib/crypt.py    2013-02-19 16:49:56.425311089 -0500
@@ -0,0 +1,71 @@
+"""Wrapper to the POSIX crypt library call and associated functionality.
+
+Note that the ``methods`` and ``METHOD_*`` attributes are non-standard
+extensions to Python 2.7, backported from 3.3"""
+
+import _crypt
+import string as _string
+from random import SystemRandom as _SystemRandom
+from collections import namedtuple as _namedtuple
+
+
+_saltchars = _string.ascii_letters + _string.digits + './'
+_sr = _SystemRandom()
+
+
+class _Method(_namedtuple('_Method', 'name ident salt_chars total_size')):
+
+    """Class representing a salt method per the Modular Crypt Format or the
+    legacy 2-character crypt method."""
+
+    def __repr__(self):
+        return '<crypt.METHOD_%s>' % self.name
+
+
+def mksalt(method=None):
+    """Generate a salt for the specified method.
+
+    If not specified, the strongest available method will be used.
+
+    This is a non-standard extension to Python 2.7, backported from 3.3
+    """
+    if method is None:
+        method = methods[0]
+    s = '$%s$' % method.ident if method.ident else ''
+    s += ''.join(_sr.sample(_saltchars, method.salt_chars))
+    return s
+
+
+def crypt(word, salt=None):
+    """Return a string representing the one-way hash of a password, with a salt
+    prepended.
+
+    If ``salt`` is not specified or is ``None``, the strongest
+    available method will be selected and a salt generated.  Otherwise,
+    ``salt`` may be one of the ``crypt.METHOD_*`` values, or a string as
+    returned by ``crypt.mksalt()``.
+
+    Note that these are non-standard extensions to Python 2.7's crypt.crypt()
+    entrypoint, backported from 3.3: the standard Python 2.7 crypt.crypt()
+    entrypoint requires two strings as the parameters, and does not support
+    keyword arguments.
+    """
+    if salt is None or isinstance(salt, _Method):
+        salt = mksalt(salt)
+    return _crypt.crypt(word, salt)
+
+
+#  available salting/crypto methods
+METHOD_CRYPT = _Method('CRYPT', None, 2, 13)
+METHOD_MD5 = _Method('MD5', '1', 8, 34)
+METHOD_SHA256 = _Method('SHA256', '5', 16, 63)
+METHOD_SHA512 = _Method('SHA512', '6', 16, 106)
+
+methods = []
+for _method in (METHOD_SHA512, METHOD_SHA256, METHOD_MD5):
+    _result = crypt('', _method)
+    if _result and len(_result) == _method.total_size:
+        methods.append(_method)
+methods.append(METHOD_CRYPT)
+del _result, _method
+
diff -up Python-2.7.3/Lib/test/test_crypt.py.crypt-module-salt-backport Python-2.7.3/Lib/test/test_crypt.py
--- Python-2.7.3/Lib/test/test_crypt.py.crypt-module-salt-backport    2012-04-09 19:07:31.000000000 -0400
+++ Python-2.7.3/Lib/test/test_crypt.py    2013-02-19 16:44:20.465334062 -0500
@@ -10,6 +10,25 @@ class CryptTestCase(unittest.TestCase):
         if test_support.verbose:
             print 'Test encryption: ', c
+    def test_salt(self):
+        self.assertEqual(len(crypt._saltchars), 64)
+        for method in crypt.methods:
+            salt = crypt.mksalt(method)
+            self.assertEqual(len(salt),
+                    method.salt_chars + (3 if method.ident else 0))
+
+    def test_saltedcrypt(self):
+        for method in crypt.methods:
+            pw = crypt.crypt('assword', method)
+            self.assertEqual(len(pw), method.total_size)
+            pw = crypt.crypt('assword', crypt.mksalt(method))
+            self.assertEqual(len(pw), method.total_size)
+
+    def test_methods(self):
+        # Gurantee that METHOD_CRYPT is the last method in crypt.methods.
+        self.assertTrue(len(crypt.methods) >= 1)
+        self.assertEqual(crypt.METHOD_CRYPT, crypt.methods[-1])
+
 def test_main():
     test_support.run_unittest(CryptTestCase)
diff -up Python-2.7.3/Modules/cryptmodule.c.crypt-module-salt-backport Python-2.7.3/Modules/cryptmodule.c
--- Python-2.7.3/Modules/cryptmodule.c.crypt-module-salt-backport    2012-04-09 19:07:34.000000000 -0400
+++ Python-2.7.3/Modules/cryptmodule.c    2013-02-19 16:44:20.466334063 -0500
@@ -43,7 +43,7 @@ static PyMethodDef crypt_methods[] = {
 };
 PyMODINIT_FUNC
-initcrypt(void)
+init_crypt(void)
 {
-    Py_InitModule("crypt", crypt_methods);
+    Py_InitModule("_crypt", crypt_methods);
 }
diff -up Python-2.7.3/Modules/Setup.dist.crypt-module-salt-backport Python-2.7.3/Modules/Setup.dist
--- Python-2.7.3/Modules/Setup.dist.crypt-module-salt-backport    2013-02-19 16:44:20.463334063 -0500
+++ Python-2.7.3/Modules/Setup.dist    2013-02-19 16:44:20.466334063 -0500
@@ -221,7 +221,7 @@ _ssl _ssl.c \
 #
 # First, look at Setup.config; configure may have set this for you.
-crypt cryptmodule.c # -lcrypt    # crypt(3); needs -lcrypt on some systems
+_crypt _cryptmodule.c -lcrypt    # crypt(3); needs -lcrypt on some systems
 # Some more UNIX dependent modules -- off by default, since these
diff -up Python-2.7.3/setup.py.crypt-module-salt-backport Python-2.7.3/setup.py
--- Python-2.7.3/setup.py.crypt-module-salt-backport    2013-02-19 16:44:20.425334067 -0500
+++ Python-2.7.3/setup.py    2013-02-19 16:44:20.466334063 -0500
@@ -693,7 +693,7 @@ class PyBuildExt(build_ext):
             libs = ['crypt']
         else:
             libs = []
-        exts.append( Extension('crypt', ['cryptmodule.c'], libraries=libs) )
+        exts.append( Extension('_crypt', ['_cryptmodule.c'], libraries=libs) )
         # CSV files
         exts.append( Extension('_csv', ['_csv.c']) )
SOURCES/00166-fix-fake-repr-in-gdb-hooks.patch
New file
@@ -0,0 +1,125 @@
diff -up Python-2.7.3/Tools/gdb/libpython.py.fix-fake-repr-in-gdb-hooks Python-2.7.3/Tools/gdb/libpython.py
--- Python-2.7.3/Tools/gdb/libpython.py.fix-fake-repr-in-gdb-hooks    2013-02-19 17:21:33.541181366 -0500
+++ Python-2.7.3/Tools/gdb/libpython.py    2013-02-19 17:21:42.090180782 -0500
@@ -105,6 +105,24 @@ class TruncatedStringIO(object):
     def getvalue(self):
         return self._val
+class FakeProxy(object):
+    """
+    Class representing a non-descript PyObject* value in the inferior
+    process for when we don't have a custom scraper, intended to have
+    a sane repr().
+    """
+    def __init__(self, tp_name, address):
+        self.tp_name = tp_name
+        self.address = address
+
+    def __repr__(self):
+        # For the NULL pointer, we have no way of knowing a type, so
+        # special-case it as per
+        # http://bugs.python.org/issue8032#msg100882
+        if self.address == 0:
+            return '0x0'
+        return '<%s at remote 0x%x>' % (self.tp_name, self.address)
+
 class PyObjectPtr(object):
     """
     Class wrapping a gdb.Value that's a either a (PyObject*) within the
@@ -232,28 +250,8 @@ class PyObjectPtr(object):
         visiting object graphs with loops).  Analogous to Py_ReprEnter and
         Py_ReprLeave
         '''
-
-        class FakeRepr(object):
-            """
-            Class representing a non-descript PyObject* value in the inferior
-            process for when we don't have a custom scraper, intended to have
-            a sane repr().
-            """
-
-            def __init__(self, tp_name, address):
-                self.tp_name = tp_name
-                self.address = address
-
-            def __repr__(self):
-                # For the NULL pointer, we have no way of knowing a type, so
-                # special-case it as per
-                # http://bugs.python.org/issue8032#msg100882
-                if self.address == 0:
-                    return '0x0'
-                return '<%s at remote 0x%x>' % (self.tp_name, self.address)
-
-        return FakeRepr(self.safe_tp_name(),
-                        long(self._gdbval))
+        return FakeProxy(self.safe_tp_name(),
+                         long(self._gdbval))
     def write_repr(self, out, visited):
         '''
@@ -384,7 +382,7 @@ def _write_instance_repr(out, visited, n
             if not first:
                 out.write(', ')
             first = False
-            out.write(pyop_arg.proxyval(visited))
+            out.write(str(pyop_arg.proxyval(visited)))
             out.write('=')
             pyop_val.write_repr(out, visited)
         out.write(')')
@@ -785,6 +783,8 @@ class PyNoneStructPtr(PyObjectPtr):
     def proxyval(self, visited):
         return None
+class CantReadFilename(ValueError):
+    pass
 class PyFrameObjectPtr(PyObjectPtr):
     _typename = 'PyFrameObject'
@@ -861,7 +861,10 @@ class PyFrameObjectPtr(PyObjectPtr):
         '''Get the path of the current Python source file, as a string'''
         if self.is_optimized_out():
             return '(frame information optimized out)'
-        return self.co_filename.proxyval(set())
+        value = self.co_filename.proxyval(set())
+        if isinstance(value, FakeProxy):
+            raise CantReadFilename('unable to extract filename)')
+        return value
     def current_line_num(self):
         '''Get current line number as an integer (1-based)
@@ -907,7 +910,7 @@ class PyFrameObjectPtr(PyObjectPtr):
                 out.write(', ')
             first = False
-            out.write(pyop_name.proxyval(visited))
+            out.write(str(pyop_name.proxyval(visited)))
             out.write('=')
             pyop_value.write_repr(out, visited)
@@ -1252,8 +1255,11 @@ class Frame(object):
             if pyop:
                 sys.stdout.write('#%i %s\n' % (self.get_index(), pyop.get_truncated_repr(MAX_OUTPUT_LEN)))
                 if not pyop.is_optimized_out():
-                    line = pyop.current_line()
-                    sys.stdout.write('    %s\n' % line.strip())
+                    try:
+                        line = pyop.current_line()
+                        sys.stdout.write('    %s\n' % line.strip())
+                    except CantReadFilename:
+                        sys.stdout.write('    %s\n' % '(unable to read filename)')
             else:
                 sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
         else:
@@ -1303,7 +1309,11 @@ class PyList(gdb.Command):
             print 'Unable to read information on python frame'
             return
-        filename = pyop.filename()
+        try:
+            filename = pyop.filename()
+        except CantReadFilename:
+            print "Unable to extract filename from python frame"
+            return
         lineno = pyop.current_line_num()
         if start is None:
SOURCES/00167-disable-stack-navigation-tests-when-optimized-in-test_gdb.patch
New file
@@ -0,0 +1,43 @@
diff -up Python-2.7.3/Lib/test/test_gdb.py.disable-stack-navigation-tests-when-optimized-in-test_gdb Python-2.7.3/Lib/test/test_gdb.py
--- Python-2.7.3/Lib/test/test_gdb.py.disable-stack-navigation-tests-when-optimized-in-test_gdb    2013-02-20 12:27:05.669526425 -0500
+++ Python-2.7.3/Lib/test/test_gdb.py    2013-02-20 12:27:05.715526422 -0500
@@ -653,10 +653,10 @@ class PyListTests(DebuggerTests):
                            '   3    def foo(a, b, c):\n',
                            bt)
+@unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
+@unittest.skipIf(python_is_optimized(),
+                "Python was compiled with optimizations")
 class StackNavigationTests(DebuggerTests):
-    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
-    @unittest.skipIf(python_is_optimized(),
-                     "Python was compiled with optimizations")
     def test_pyup_command(self):
         'Verify that the "py-up" command works'
         bt = self.get_stack_trace(script=self.get_sample_script(),
@@ -667,7 +667,6 @@ class StackNavigationTests(DebuggerTests
     baz\(a, b, c\)
 $''')
-    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
     def test_down_at_bottom(self):
         'Verify handling of "py-down" at the bottom of the stack'
         bt = self.get_stack_trace(script=self.get_sample_script(),
@@ -675,7 +674,6 @@ $''')
         self.assertEndsWith(bt,
                             'Unable to find a newer python frame\n')
-    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
     def test_up_at_top(self):
         'Verify handling of "py-up" at the top of the stack'
         bt = self.get_stack_trace(script=self.get_sample_script(),
@@ -683,9 +681,6 @@ $''')
         self.assertEndsWith(bt,
                             'Unable to find an older python frame\n')
-    @unittest.skipUnless(HAS_PYUP_PYDOWN, "test requires py-up/py-down commands")
-    @unittest.skipIf(python_is_optimized(),
-                     "Python was compiled with optimizations")
     def test_up_then_down(self):
         'Verify "py-up" followed by "py-down"'
         bt = self.get_stack_trace(script=self.get_sample_script(),
SOURCES/00168-distutils-cflags.patch
New file
@@ -0,0 +1,12 @@
diff -up Python-2.6.6/Lib/distutils/sysconfig.py.distutils-cflags Python-2.6.6/Lib/distutils/sysconfig.py
--- Python-2.6.6/Lib/distutils/sysconfig.py.distutils-cflags    2011-08-12 17:18:17.833091153 -0400
+++ Python-2.6.6/Lib/distutils/sysconfig.py    2011-08-12 17:18:27.449106938 -0400
@@ -187,7 +187,7 @@ def customize_compiler(compiler):
         if 'LDFLAGS' in os.environ:
             ldshared = ldshared + ' ' + os.environ['LDFLAGS']
         if 'CFLAGS' in os.environ:
-            cflags = opt + ' ' + os.environ['CFLAGS']
+            cflags = cflags + ' ' + os.environ['CFLAGS']
             ldshared = ldshared + ' ' + os.environ['CFLAGS']
         if 'CPPFLAGS' in os.environ:
             cpp = cpp + ' ' + os.environ['CPPFLAGS']
SOURCES/00169-avoid-implicit-usage-of-md5-in-multiprocessing.patch
New file
@@ -0,0 +1,41 @@
diff --git a/Lib/multiprocessing/connection.py b/Lib/multiprocessing/connection.py
--- a/Lib/multiprocessing/connection.py
+++ b/Lib/multiprocessing/connection.py
@@ -41,6 +41,10 @@
 # A very generous timeout when it comes to local connections...
 CONNECTION_TIMEOUT = 20.
+# The hmac module implicitly defaults to using MD5.
+# Support using a stronger algorithm for the challenge/response code:
+HMAC_DIGEST_NAME='sha256'
+
 _mmap_counter = itertools.count()
 default_family = 'AF_INET'
@@ -700,12 +704,16 @@
 WELCOME = b'#WELCOME#'
 FAILURE = b'#FAILURE#'
+def get_digestmod_for_hmac():
+    import hashlib
+    return getattr(hashlib, HMAC_DIGEST_NAME)
+
 def deliver_challenge(connection, authkey):
     import hmac
     assert isinstance(authkey, bytes)
     message = os.urandom(MESSAGE_LENGTH)
     connection.send_bytes(CHALLENGE + message)
-    digest = hmac.new(authkey, message).digest()
+    digest = hmac.new(authkey, message, get_digestmod_for_hmac()).digest()
     response = connection.recv_bytes(256)        # reject large message
     if response == digest:
         connection.send_bytes(WELCOME)
@@ -719,7 +727,7 @@
     message = connection.recv_bytes(256)         # reject large message
     assert message[:len(CHALLENGE)] == CHALLENGE, 'message = %r' % message
     message = message[len(CHALLENGE):]
-    digest = hmac.new(authkey, message).digest()
+    digest = hmac.new(authkey, message, get_digestmod_for_hmac()).digest()
     connection.send_bytes(digest)
     response = connection.recv_bytes(256)        # reject large message
     if response != WELCOME:
SOURCES/00170-gc-assertions.patch
New file
@@ -0,0 +1,276 @@
diff -up Python-2.7.3/Lib/test/test_gc.py.gc-assertions Python-2.7.3/Lib/test/test_gc.py
--- Python-2.7.3/Lib/test/test_gc.py.gc-assertions    2013-02-20 16:28:20.890536607 -0500
+++ Python-2.7.3/Lib/test/test_gc.py    2013-02-20 16:39:52.720489297 -0500
@@ -1,6 +1,7 @@
 import unittest
-from test.test_support import verbose, run_unittest
+from test.test_support import verbose, run_unittest, import_module
 import sys
+import sysconfig
 import time
 import gc
 import weakref
@@ -32,6 +33,8 @@ class GC_Detector(object):
         self.wr = weakref.ref(C1055820(666), it_happened)
+BUILT_WITH_NDEBUG = ('-DNDEBUG' in sysconfig.get_config_vars()['PY_CFLAGS'])
+
 ### Tests
 ###############################################################################
@@ -476,6 +479,49 @@ class GCTests(unittest.TestCase):
             # would be damaged, with an empty __dict__.
             self.assertEqual(x, None)
+    @unittest.skipIf(BUILT_WITH_NDEBUG,
+                     'built with -NDEBUG')
+    def test_refcount_errors(self):
+        # Verify the "handling" of objects with broken refcounts
+
+        import_module("ctypes") #skip if not supported
+
+        import subprocess
+        code = '''if 1:
+        a = []
+        b = [a]
+
+        # Simulate the refcount of "a" being too low (compared to the
+        # references held on it by live data), but keeping it above zero
+        # (to avoid deallocating it):
+        import ctypes
+        ctypes.pythonapi.Py_DecRef(ctypes.py_object(a))
+
+        # The garbage collector should now have a fatal error when it reaches
+        # the broken object:
+        import gc
+        gc.collect()
+        '''
+        p = subprocess.Popen([sys.executable, "-c", code],
+                             stdout=subprocess.PIPE,
+                             stderr=subprocess.PIPE)
+        stdout, stderr = p.communicate()
+        p.stdout.close()
+        p.stderr.close()
+        # Verify that stderr has a useful error message:
+        self.assertRegexpMatches(stderr,
+            b'Modules/gcmodule.c:[0-9]+: visit_decref: Assertion "gc->gc.gc_refs != 0" failed.')
+        self.assertRegexpMatches(stderr,
+            b'refcount was too small')
+        self.assertRegexpMatches(stderr,
+            b'object  : \[\]')
+        self.assertRegexpMatches(stderr,
+            b'type    : list')
+        self.assertRegexpMatches(stderr,
+            b'refcount: 1')
+        self.assertRegexpMatches(stderr,
+            b'address : 0x[0-9a-f]+')
+
 class GCTogglingTests(unittest.TestCase):
     def setUp(self):
         gc.enable()
diff -up Python-2.7.3/Modules/gcmodule.c.gc-assertions Python-2.7.3/Modules/gcmodule.c
--- Python-2.7.3/Modules/gcmodule.c.gc-assertions    2012-04-09 19:07:34.000000000 -0400
+++ Python-2.7.3/Modules/gcmodule.c    2013-02-20 16:28:21.029536600 -0500
@@ -21,6 +21,73 @@
 #include "Python.h"
 #include "frameobject.h"        /* for PyFrame_ClearFreeList */
+/*
+   Define a pair of assertion macros.
+
+   These work like the regular C assert(), in that they will abort the
+   process with a message on stderr if the given condition fails to hold,
+   but compile away to nothing if NDEBUG is defined.
+
+   However, before aborting, Python will also try to call _PyObject_Dump() on
+   the given object.  This may be of use when investigating bugs in which a
+   particular object is corrupt (e.g. buggy a tp_visit method in an extension
+   module breaking the garbage collector), to help locate the broken objects.
+
+   The WITH_MSG variant allows you to supply an additional message that Python
+   will attempt to print to stderr, after the object dump.
+*/
+#ifdef NDEBUG
+/* No debugging: compile away the assertions: */
+#define PyObject_ASSERT_WITH_MSG(obj, expr, msg) ((void)0)
+#else
+/* With debugging: generate checks: */
+#define PyObject_ASSERT_WITH_MSG(obj, expr, msg) \
+  ((expr)                                           \
+   ? (void)(0)                                      \
+   : _PyObject_AssertFailed((obj),                  \
+                            (msg),                  \
+                            (__STRING(expr)),       \
+                            (__FILE__),             \
+                            (__LINE__),             \
+                            (__PRETTY_FUNCTION__)))
+#endif
+
+#define PyObject_ASSERT(obj, expr) \
+  PyObject_ASSERT_WITH_MSG(obj, expr, NULL)
+
+static void _PyObject_AssertFailed(PyObject *,  const char *,
+                   const char *, const char *, int,
+                   const char *);
+
+static void
+_PyObject_AssertFailed(PyObject *obj, const char *msg, const char *expr,
+               const char *file, int line, const char *function)
+{
+    fprintf(stderr,
+            "%s:%d: %s: Assertion \"%s\" failed.\n",
+            file, line, function, expr);
+    if (msg) {
+        fprintf(stderr, "%s\n", msg);
+    }
+
+    fflush(stderr);
+
+    if (obj) {
+        /* This might succeed or fail, but we're about to abort, so at least
+           try to provide any extra info we can: */
+        _PyObject_Dump(obj);
+    }
+    else {
+        fprintf(stderr, "NULL object\n");
+    }
+
+    fflush(stdout);
+    fflush(stderr);
+
+    /* Terminate the process: */
+    abort();
+}
+
 /* Get an object's GC head */
 #define AS_GC(o) ((PyGC_Head *)(o)-1)
@@ -288,7 +355,8 @@ update_refs(PyGC_Head *containers)
 {
     PyGC_Head *gc = containers->gc.gc_next;
     for (; gc != containers; gc = gc->gc.gc_next) {
-        assert(gc->gc.gc_refs == GC_REACHABLE);
+        PyObject_ASSERT(FROM_GC(gc),
+                        gc->gc.gc_refs == GC_REACHABLE);
         gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
         /* Python's cyclic gc should never see an incoming refcount
          * of 0:  if something decref'ed to 0, it should have been
@@ -308,7 +376,8 @@ update_refs(PyGC_Head *containers)
          * so serious that maybe this should be a release-build
          * check instead of an assert?
          */
-        assert(gc->gc.gc_refs != 0);
+        PyObject_ASSERT(FROM_GC(gc),
+                        gc->gc.gc_refs != 0);
     }
 }
@@ -323,7 +392,9 @@ visit_decref(PyObject *op, void *data)
          * generation being collected, which can be recognized
          * because only they have positive gc_refs.
          */
-        assert(gc->gc.gc_refs != 0); /* else refcount was too small */
+        PyObject_ASSERT_WITH_MSG(FROM_GC(gc),
+                                 gc->gc.gc_refs != 0,
+                                 "refcount was too small");
         if (gc->gc.gc_refs > 0)
             gc->gc.gc_refs--;
     }
@@ -383,9 +454,10 @@ visit_reachable(PyObject *op, PyGC_Head
          * If gc_refs == GC_UNTRACKED, it must be ignored.
          */
          else {
-            assert(gc_refs > 0
-                   || gc_refs == GC_REACHABLE
-                   || gc_refs == GC_UNTRACKED);
+             PyObject_ASSERT(FROM_GC(gc),
+                             gc_refs > 0
+                             || gc_refs == GC_REACHABLE
+                             || gc_refs == GC_UNTRACKED);
          }
     }
     return 0;
@@ -427,7 +499,7 @@ move_unreachable(PyGC_Head *young, PyGC_
              */
             PyObject *op = FROM_GC(gc);
             traverseproc traverse = Py_TYPE(op)->tp_traverse;
-            assert(gc->gc.gc_refs > 0);
+            PyObject_ASSERT(op, gc->gc.gc_refs > 0);
             gc->gc.gc_refs = GC_REACHABLE;
             (void) traverse(op,
                             (visitproc)visit_reachable,
@@ -494,7 +566,8 @@ move_finalizers(PyGC_Head *unreachable,
     for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
         PyObject *op = FROM_GC(gc);
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
+
         next = gc->gc.gc_next;
         if (has_finalizer(op)) {
@@ -570,7 +643,7 @@ handle_weakrefs(PyGC_Head *unreachable,
         PyWeakReference **wrlist;
         op = FROM_GC(gc);
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
         next = gc->gc.gc_next;
         if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
@@ -591,9 +664,9 @@ handle_weakrefs(PyGC_Head *unreachable,
              * the callback pointer intact.  Obscure:  it also
              * changes *wrlist.
              */
-            assert(wr->wr_object == op);
+            PyObject_ASSERT(wr->wr_object, wr->wr_object == op);
             _PyWeakref_ClearRef(wr);
-            assert(wr->wr_object == Py_None);
+            PyObject_ASSERT(wr->wr_object, wr->wr_object == Py_None);
             if (wr->wr_callback == NULL)
                 continue;                       /* no callback */
@@ -627,7 +700,7 @@ handle_weakrefs(PyGC_Head *unreachable,
      */
             if (IS_TENTATIVELY_UNREACHABLE(wr))
                 continue;
-            assert(IS_REACHABLE(wr));
+            PyObject_ASSERT(op, IS_REACHABLE(wr));
             /* Create a new reference so that wr can't go away
              * before we can process it again.
@@ -636,7 +709,8 @@ handle_weakrefs(PyGC_Head *unreachable,
             /* Move wr to wrcb_to_call, for the next pass. */
             wrasgc = AS_GC(wr);
-            assert(wrasgc != next); /* wrasgc is reachable, but
+            PyObject_ASSERT(op, wrasgc != next);
+                                    /* wrasgc is reachable, but
                                        next isn't, so they can't
                                        be the same */
             gc_list_move(wrasgc, &wrcb_to_call);
@@ -652,11 +726,11 @@ handle_weakrefs(PyGC_Head *unreachable,
         gc = wrcb_to_call.gc.gc_next;
         op = FROM_GC(gc);
-        assert(IS_REACHABLE(op));
-        assert(PyWeakref_Check(op));
+        PyObject_ASSERT(op, IS_REACHABLE(op));
+        PyObject_ASSERT(op, PyWeakref_Check(op));
         wr = (PyWeakReference *)op;
         callback = wr->wr_callback;
-        assert(callback != NULL);
+        PyObject_ASSERT(op, callback != NULL);
         /* copy-paste of weakrefobject.c's handle_callback() */
         temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
@@ -759,7 +833,7 @@ delete_garbage(PyGC_Head *collectable, P
         PyGC_Head *gc = collectable->gc.gc_next;
         PyObject *op = FROM_GC(gc);
-        assert(IS_TENTATIVELY_UNREACHABLE(op));
+        PyObject_ASSERT(op, IS_TENTATIVELY_UNREACHABLE(op));
         if (debug & DEBUG_SAVEALL) {
             PyList_Append(garbage, op);
         }
SOURCES/00173-workaround-ENOPROTOOPT-in-bind_port.patch
New file
@@ -0,0 +1,13 @@
diff -up Python-2.7.3/Lib/test/test_support.py.rhbz913732 Python-2.7.3/Lib/test/test_support.py
--- Python-2.7.3/Lib/test/test_support.py.rhbz913732    2013-03-04 16:11:53.757315921 -0500
+++ Python-2.7.3/Lib/test/test_support.py    2013-03-04 16:12:11.331314722 -0500
@@ -304,7 +304,8 @@ def bind_port(sock, host=HOST):
             if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) == 1:
                 raise TestFailed("tests should never set the SO_REUSEADDR "   \
                                  "socket option on TCP/IP sockets!")
-        if hasattr(socket, 'SO_REUSEPORT'):
+        if hasattr(socket, 'SO_REUSEPORT') \
+                and 'WITHIN_PYTHON_RPM_BUILD' not in os.environ: # rhbz#913732
             if sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT) == 1:
                 raise TestFailed("tests should never set the SO_REUSEPORT "   \
                                  "socket option on TCP/IP sockets!")
SOURCES/00174-fix-for-usr-move.patch
New file
@@ -0,0 +1,28 @@
diff -up Python-2.7.3/Modules/getpath.c.fix-for-usr-move Python-2.7.3/Modules/getpath.c
--- Python-2.7.3/Modules/getpath.c.fix-for-usr-move    2013-03-06 14:25:32.801828698 -0500
+++ Python-2.7.3/Modules/getpath.c    2013-03-06 15:59:30.872443168 -0500
@@ -510,6 +510,24 @@ calculate_path(void)
        MAXPATHLEN bytes long.
     */
+    /*
+      Workaround for rhbz#817554, where an empty argv0_path erroneously
+      locates "prefix" as "/lib[64]/python2.7" due to it finding
+      "/lib[64]/python2.7/os.py" via the /lib -> /usr/lib symlink for
+      https://fedoraproject.org/wiki/Features/UsrMove
+    */
+    if (argv0_path[0] == '\0' && 0 == strcmp(prog, "cmpi_swig")) {
+        /*
+          We have an empty argv0_path, presumably because prog aka
+          Py_GetProgramName() was not found on $PATH.
+
+          Set argv0_path to "/usr/" so that search_for_prefix() and
+          search_for_exec_prefix() don't erroneously pick up
+          on /lib/ via the UsrMove symlink:
+        */
+        strcpy(argv0_path, "/usr/");
+    }
+
     if (!(pfound = search_for_prefix(argv0_path, home))) {
         if (!Py_FrozenFlag)
             fprintf(stderr,
SOURCES/00180-python-add-support-for-ppc64p7.patch
New file
@@ -0,0 +1,12 @@
diff -r de35eae9048a config.sub
--- a/config.sub    Wed Apr 24 23:33:20 2013 +0200
+++ b/config.sub    Thu Apr 25 08:51:00 2013 +0200
@@ -1008,7 +1008,7 @@
         ;;
     ppc64)    basic_machine=powerpc64-unknown
         ;;
-    ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
+    ppc64-* | ppc64p7-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'`
         ;;
     ppc64le | powerpc64little | ppc64-le | powerpc64-little)
         basic_machine=powerpc64le-unknown
SOURCES/00181-allow-arbitrary-timeout-in-condition-wait.patch
New file
@@ -0,0 +1,70 @@
diff --git a/Lib/threading.py b/Lib/threading.py
index cb49c4a..c9795a5 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -305,7 +305,7 @@ class _Condition(_Verbose):
         else:
             return True
-    def wait(self, timeout=None):
+    def wait(self, timeout=None, balancing=True):
         """Wait until notified or until a timeout occurs.
         If the calling thread has not acquired the lock when this method is
@@ -354,7 +354,10 @@ class _Condition(_Verbose):
                     remaining = endtime - _time()
                     if remaining <= 0:
                         break
-                    delay = min(delay * 2, remaining, .05)
+                    if balancing:
+                        delay = min(delay * 2, remaining, 0.05)
+                    else:
+                        delay = remaining
                     _sleep(delay)
                 if not gotit:
                     if __debug__:
@@ -599,7 +602,7 @@ class _Event(_Verbose):
         finally:
             self.__cond.release()
-    def wait(self, timeout=None):
+    def wait(self, timeout=None, balancing=True):
         """Block until the internal flag is true.
         If the internal flag is true on entry, return immediately. Otherwise,
@@ -617,7 +620,7 @@ class _Event(_Verbose):
         self.__cond.acquire()
         try:
             if not self.__flag:
-                self.__cond.wait(timeout)
+                self.__cond.wait(timeout, balancing)
             return self.__flag
         finally:
             self.__cond.release()
@@ -908,7 +911,7 @@ class Thread(_Verbose):
             if 'dummy_threading' not in _sys.modules:
                 raise
-    def join(self, timeout=None):
+    def join(self, timeout=None, balancing=True):
         """Wait until the thread terminates.
         This blocks the calling thread until the thread whose join() method is
@@ -957,7 +960,7 @@ class Thread(_Verbose):
                         if __debug__:
                             self._note("%s.join(): timed out", self)
                         break
-                    self.__block.wait(delay)
+                    self.__block.wait(delay, balancing)
                 else:
                     if __debug__:
                         self._note("%s.join(): thread stopped", self)
@@ -1143,7 +1146,7 @@ class _DummyThread(Thread):
     def _set_daemon(self):
         return True
-    def join(self, timeout=None):
+    def join(self, timeout=None, balancing=True):
         assert False, "cannot join a dummy thread"
SOURCES/00184-ctypes-should-build-with-libffi-multilib-wrapper.patch
New file
@@ -0,0 +1,13 @@
diff -up Python-2.7.5/setup.py.orig Python-2.7.5/setup.py
--- Python-2.7.5/setup.py.orig    2013-07-17 15:20:12.086820082 +0200
+++ Python-2.7.5/setup.py    2013-07-17 15:21:28.490023903 +0200
@@ -2050,7 +2050,8 @@ class PyBuildExt(build_ext):
                 if not line:
                     ffi_inc = None
                     break
-                if line.startswith('#define LIBFFI_H'):
+                if line.startswith('#define LIBFFI_H') or \
+                   line.startswith('#define ffi_wrapper_h'):
                     break
         ffi_lib = None
         if ffi_inc is not None:
SOURCES/00185-urllib2-honors-noproxy-for-ftp.patch
New file
@@ -0,0 +1,12 @@
diff -up Python-2.7.5/Lib/urllib2.py.orig Python-2.7.5/Lib/urllib2.py
--- Python-2.7.5/Lib/urllib2.py.orig    2013-07-17 12:22:58.595525622 +0200
+++ Python-2.7.5/Lib/urllib2.py    2013-07-17 12:19:59.875898030 +0200
@@ -728,6 +728,8 @@ class ProxyHandler(BaseHandler):
         if proxy_type is None:
             proxy_type = orig_type
+        req.get_host()
+
         if req.host and proxy_bypass(req.host):
             return None
SOURCES/00186-memory-leak-marshalc.patch
New file
@@ -0,0 +1,57 @@
--- Python-2.7.5/Python/marshal.c    2013-05-12 05:32:53.000000000 +0200
+++ /home/rkuska/hg/cpython/Python/marshal.c    2013-07-18 10:33:26.392486235 +0200
@@ -88,7 +88,7 @@
 }
 static void
-w_string(char *s, Py_ssize_t n, WFILE *p)
+w_string(const char *s, Py_ssize_t n, WFILE *p)
 {
     if (p->fp != NULL) {
         fwrite(s, 1, n, p->fp);
@@ -141,6 +141,13 @@
 # define W_SIZE  w_long
 #endif
+static void
+w_pstring(const char *s, Py_ssize_t n, WFILE *p)
+{
+        W_SIZE(n, p);
+        w_string(s, n, p);
+}
+
 /* We assume that Python longs are stored internally in base some power of
    2**15; for the sake of portability we'll always read and write them in base
    exactly 2**15. */
@@ -338,9 +345,7 @@
         else {
             w_byte(TYPE_STRING, p);
         }
-        n = PyString_GET_SIZE(v);
-        W_SIZE(n, p);
-        w_string(PyString_AS_STRING(v), n, p);
+        w_pstring(PyBytes_AS_STRING(v), PyString_GET_SIZE(v), p);
     }
 #ifdef Py_USING_UNICODE
     else if (PyUnicode_CheckExact(v)) {
@@ -352,9 +357,7 @@
             return;
         }
         w_byte(TYPE_UNICODE, p);
-        n = PyString_GET_SIZE(utf8);
-        W_SIZE(n, p);
-        w_string(PyString_AS_STRING(utf8), n, p);
+        w_pstring(PyString_AS_STRING(utf8), PyString_GET_SIZE(utf8), p);
         Py_DECREF(utf8);
     }
 #endif
@@ -441,8 +444,7 @@
         PyBufferProcs *pb = v->ob_type->tp_as_buffer;
         w_byte(TYPE_STRING, p);
         n = (*pb->bf_getreadbuffer)(v, 0, (void **)&s);
-        W_SIZE(n, p);
-        w_string(s, n, p);
+        w_pstring(s, n, p);
     }
     else {
         w_byte(TYPE_UNKNOWN, p);
SOURCES/00187-add-RPATH-to-pyexpat.patch
New file
@@ -0,0 +1,25 @@
diff -r e8b8279ca118 setup.py
--- a/setup.py    Sun Jul 21 21:57:52 2013 -0400
+++ b/setup.py    Tue Aug 20 09:45:31 2013 +0200
@@ -1480,12 +1480,21 @@
                              'expat/xmltok_impl.h'
                              ]
+        # Add an explicit RPATH to pyexpat.so pointing at the directory
+        # containing the system expat (which has the extra XML_SetHashSalt
+        # symbol), to avoid an ImportError with a link error if there's an
+        # LD_LIBRARY_PATH containing a "vanilla" build of expat (without the
+        # symbol) (rhbz#833271):
+        EXPAT_RPATH = '/usr/lib64' if sys.maxint == 0x7fffffffffffffff else '/usr/lib'
+
+
         exts.append(Extension('pyexpat',
                               define_macros = define_macros,
                               include_dirs = expat_inc,
                               libraries = expat_lib,
                               sources = ['pyexpat.c'] + expat_sources,
                               depends = expat_depends,
+                              extra_link_args = ['-Wl,-rpath,%s' % EXPAT_RPATH]
                               ))
         # Fredrik Lundh's cElementTree module.  Note that this also
SOURCES/00188-CVE-2013-4238-hostname-check-bypass-in-SSL-module.patch
New file
@@ -0,0 +1,247 @@
diff -r 9ddc63c039ba Lib/test/nullbytecert.pem
--- /dev/null    Thu Jan 01 00:00:00 1970 +0000
+++ b/Lib/test/nullbytecert.pem    Sun Aug 11 18:13:17 2013 +0200
@@ -0,0 +1,90 @@
+Certificate:
+    Data:
+        Version: 3 (0x2)
+        Serial Number: 0 (0x0)
+    Signature Algorithm: sha1WithRSAEncryption
+        Issuer: C=US, ST=Oregon, L=Beaverton, O=Python Software Foundation, OU=Python Core Development, CN=null.python.org\x00example.org/emailAddress=python-dev@python.org
+        Validity
+            Not Before: Aug  7 13:11:52 2013 GMT
+            Not After : Aug  7 13:12:52 2013 GMT
+        Subject: C=US, ST=Oregon, L=Beaverton, O=Python Software Foundation, OU=Python Core Development, CN=null.python.org\x00example.org/emailAddress=python-dev@python.org
+        Subject Public Key Info:
+            Public Key Algorithm: rsaEncryption
+                Public-Key: (2048 bit)
+                Modulus:
+                    00:b5:ea:ed:c9:fb:46:7d:6f:3b:76:80:dd:3a:f3:
+                    03:94:0b:a7:a6:db:ec:1d:df:ff:23:74:08:9d:97:
+                    16:3f:a3:a4:7b:3e:1b:0e:96:59:25:03:a7:26:e2:
+                    88:a9:cf:79:cd:f7:04:56:b0:ab:79:32:6e:59:c1:
+                    32:30:54:eb:58:a8:cb:91:f0:42:a5:64:27:cb:d4:
+                    56:31:88:52:ad:cf:bd:7f:f0:06:64:1f:cc:27:b8:
+                    a3:8b:8c:f3:d8:29:1f:25:0b:f5:46:06:1b:ca:02:
+                    45:ad:7b:76:0a:9c:bf:bb:b9:ae:0d:16:ab:60:75:
+                    ae:06:3e:9c:7c:31:dc:92:2f:29:1a:e0:4b:0c:91:
+                    90:6c:e9:37:c5:90:d7:2a:d7:97:15:a3:80:8f:5d:
+                    7b:49:8f:54:30:d4:97:2c:1c:5b:37:b5:ab:69:30:
+                    68:43:d3:33:78:4b:02:60:f5:3c:44:80:a1:8f:e7:
+                    f0:0f:d1:5e:87:9e:46:cf:62:fc:f9:bf:0c:65:12:
+                    f1:93:c8:35:79:3f:c8:ec:ec:47:f5:ef:be:44:d5:
+                    ae:82:1e:2d:9a:9f:98:5a:67:65:e1:74:70:7c:cb:
+                    d3:c2:ce:0e:45:49:27:dc:e3:2d:d4:fb:48:0e:2f:
+                    9e:77:b8:14:46:c0:c4:36:ca:02:ae:6a:91:8c:da:
+                    2f:85
+                Exponent: 65537 (0x10001)
+        X509v3 extensions:
+            X509v3 Basic Constraints: critical
+                CA:FALSE
+            X509v3 Subject Key Identifier:
+                88:5A:55:C0:52:FF:61:CD:52:A3:35:0F:EA:5A:9C:24:38:22:F7:5C
+            X509v3 Key Usage:
+                Digital Signature, Non Repudiation, Key Encipherment
+            X509v3 Subject Alternative Name:
+                *************************************************************
+                WARNING: The values for DNS, email and URI are WRONG. OpenSSL
+                         doesn't print the text after a NULL byte.
+                *************************************************************
+                DNS:altnull.python.org, email:null@python.org, URI:http://null.python.org, IP Address:192.0.2.1, IP Address:2001:DB8:0:0:0:0:0:1
+    Signature Algorithm: sha1WithRSAEncryption
+         ac:4f:45:ef:7d:49:a8:21:70:8e:88:59:3e:d4:36:42:70:f5:
+         a3:bd:8b:d7:a8:d0:58:f6:31:4a:b1:a4:a6:dd:6f:d9:e8:44:
+         3c:b6:0a:71:d6:7f:b1:08:61:9d:60:ce:75:cf:77:0c:d2:37:
+         86:02:8d:5e:5d:f9:0f:71:b4:16:a8:c1:3d:23:1c:f1:11:b3:
+         56:6e:ca:d0:8d:34:94:e6:87:2a:99:f2:ae:ae:cc:c2:e8:86:
+         de:08:a8:7f:c5:05:fa:6f:81:a7:82:e6:d0:53:9d:34:f4:ac:
+         3e:40:fe:89:57:7a:29:a4:91:7e:0b:c6:51:31:e5:10:2f:a4:
+         60:76:cd:95:51:1a:be:8b:a1:b0:fd:ad:52:bd:d7:1b:87:60:
+         d2:31:c7:17:c4:18:4f:2d:08:25:a3:a7:4f:b7:92:ca:e2:f5:
+         25:f1:54:75:81:9d:b3:3d:61:a2:f7:da:ed:e1:c6:6f:2c:60:
+         1f:d8:6f:c5:92:05:ab:c9:09:62:49:a9:14:ad:55:11:cc:d6:
+         4a:19:94:99:97:37:1d:81:5f:8b:cf:a3:a8:96:44:51:08:3d:
+         0b:05:65:12:eb:b6:70:80:88:48:72:4f:c6:c2:da:cf:cd:8e:
+         5b:ba:97:2f:60:b4:96:56:49:5e:3a:43:76:63:04:be:2a:f6:
+         c1:ca:a9:94
+-----BEGIN CERTIFICATE-----
+MIIE2DCCA8CgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBxTELMAkGA1UEBhMCVVMx
+DzANBgNVBAgMBk9yZWdvbjESMBAGA1UEBwwJQmVhdmVydG9uMSMwIQYDVQQKDBpQ
+eXRob24gU29mdHdhcmUgRm91bmRhdGlvbjEgMB4GA1UECwwXUHl0aG9uIENvcmUg
+RGV2ZWxvcG1lbnQxJDAiBgNVBAMMG251bGwucHl0aG9uLm9yZwBleGFtcGxlLm9y
+ZzEkMCIGCSqGSIb3DQEJARYVcHl0aG9uLWRldkBweXRob24ub3JnMB4XDTEzMDgw
+NzEzMTE1MloXDTEzMDgwNzEzMTI1MlowgcUxCzAJBgNVBAYTAlVTMQ8wDQYDVQQI
+DAZPcmVnb24xEjAQBgNVBAcMCUJlYXZlcnRvbjEjMCEGA1UECgwaUHl0aG9uIFNv
+ZnR3YXJlIEZvdW5kYXRpb24xIDAeBgNVBAsMF1B5dGhvbiBDb3JlIERldmVsb3Bt
+ZW50MSQwIgYDVQQDDBtudWxsLnB5dGhvbi5vcmcAZXhhbXBsZS5vcmcxJDAiBgkq
+hkiG9w0BCQEWFXB5dGhvbi1kZXZAcHl0aG9uLm9yZzCCASIwDQYJKoZIhvcNAQEB
+BQADggEPADCCAQoCggEBALXq7cn7Rn1vO3aA3TrzA5QLp6bb7B3f/yN0CJ2XFj+j
+pHs+Gw6WWSUDpybiiKnPec33BFawq3kyblnBMjBU61ioy5HwQqVkJ8vUVjGIUq3P
+vX/wBmQfzCe4o4uM89gpHyUL9UYGG8oCRa17dgqcv7u5rg0Wq2B1rgY+nHwx3JIv
+KRrgSwyRkGzpN8WQ1yrXlxWjgI9de0mPVDDUlywcWze1q2kwaEPTM3hLAmD1PESA
+oY/n8A/RXoeeRs9i/Pm/DGUS8ZPINXk/yOzsR/XvvkTVroIeLZqfmFpnZeF0cHzL
+08LODkVJJ9zjLdT7SA4vnne4FEbAxDbKAq5qkYzaL4UCAwEAAaOB0DCBzTAMBgNV
+HRMBAf8EAjAAMB0GA1UdDgQWBBSIWlXAUv9hzVKjNQ/qWpwkOCL3XDALBgNVHQ8E
+BAMCBeAwgZAGA1UdEQSBiDCBhYIeYWx0bnVsbC5weXRob24ub3JnAGV4YW1wbGUu
+Y29tgSBudWxsQHB5dGhvbi5vcmcAdXNlckBleGFtcGxlLm9yZ4YpaHR0cDovL251
+bGwucHl0aG9uLm9yZwBodHRwOi8vZXhhbXBsZS5vcmeHBMAAAgGHECABDbgAAAAA
+AAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAKxPRe99SaghcI6IWT7UNkJw9aO9
+i9eo0Fj2MUqxpKbdb9noRDy2CnHWf7EIYZ1gznXPdwzSN4YCjV5d+Q9xtBaowT0j
+HPERs1ZuytCNNJTmhyqZ8q6uzMLoht4IqH/FBfpvgaeC5tBTnTT0rD5A/olXeimk
+kX4LxlEx5RAvpGB2zZVRGr6LobD9rVK91xuHYNIxxxfEGE8tCCWjp0+3ksri9SXx
+VHWBnbM9YaL32u3hxm8sYB/Yb8WSBavJCWJJqRStVRHM1koZlJmXNx2BX4vPo6iW
+RFEIPQsFZRLrtnCAiEhyT8bC2s/Njlu6ly9gtJZWSV46Q3ZjBL4q9sHKqZQ=
+-----END CERTIFICATE-----
diff -r 9ddc63c039ba Lib/test/test_ssl.py
--- a/Lib/test/test_ssl.py    Sun Aug 11 13:04:50 2013 +0300
+++ b/Lib/test/test_ssl.py    Sun Aug 11 18:13:17 2013 +0200
@@ -25,6 +25,7 @@
 HOST = test_support.HOST
 CERTFILE = None
 SVN_PYTHON_ORG_ROOT_CERT = None
+NULLBYTECERT = None
 def handle_error(prefix):
     exc_format = ' '.join(traceback.format_exception(*sys.exc_info()))
@@ -123,6 +124,27 @@
                           ('DNS', 'projects.forum.nokia.com'))
                         )
+    def test_parse_cert_CVE_2013_4073(self):
+        p = ssl._ssl._test_decode_cert(NULLBYTECERT)
+        if test_support.verbose:
+            sys.stdout.write("\n" + pprint.pformat(p) + "\n")
+        subject = ((('countryName', 'US'),),
+                   (('stateOrProvinceName', 'Oregon'),),
+                   (('localityName', 'Beaverton'),),
+                   (('organizationName', 'Python Software Foundation'),),
+                   (('organizationalUnitName', 'Python Core Development'),),
+                   (('commonName', 'null.python.org\x00example.org'),),
+                   (('emailAddress', 'python-dev@python.org'),))
+        self.assertEqual(p['subject'], subject)
+        self.assertEqual(p['issuer'], subject)
+        self.assertEqual(p['subjectAltName'],
+                         (('DNS', 'altnull.python.org\x00example.com'),
+                         ('email', 'null@python.org\x00user@example.org'),
+                         ('URI', 'http://null.python.org\x00http://example.org'),
+                         ('IP Address', '192.0.2.1'),
+                         ('IP Address', '2001:DB8:0:0:0:0:0:1\n'))
+                        )
+
     def test_DER_to_PEM(self):
         with open(SVN_PYTHON_ORG_ROOT_CERT, 'r') as f:
             pem = f.read()
@@ -1360,7 +1382,7 @@
 def test_main(verbose=False):
-    global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT
+    global CERTFILE, SVN_PYTHON_ORG_ROOT_CERT, NOKIACERT, NULLBYTECERT
     CERTFILE = os.path.join(os.path.dirname(__file__) or os.curdir,
                             "keycert.pem")
     SVN_PYTHON_ORG_ROOT_CERT = os.path.join(
@@ -1368,10 +1390,13 @@
         "https_svn_python_org_root.pem")
     NOKIACERT = os.path.join(os.path.dirname(__file__) or os.curdir,
                              "nokia.pem")
+    NULLBYTECERT = os.path.join(os.path.dirname(__file__) or os.curdir,
+                                "nullbytecert.pem")
     if (not os.path.exists(CERTFILE) or
         not os.path.exists(SVN_PYTHON_ORG_ROOT_CERT) or
-        not os.path.exists(NOKIACERT)):
+        not os.path.exists(NOKIACERT) or
+        not os.path.exists(NULLBYTECERT)):
         raise test_support.TestFailed("Can't read certificate files!")
     tests = [BasicTests, BasicSocketTests]
diff -r 9ddc63c039ba Modules/_ssl.c
--- a/Modules/_ssl.c    Sun Aug 11 13:04:50 2013 +0300
+++ b/Modules/_ssl.c    Sun Aug 11 18:13:17 2013 +0200
@@ -741,8 +741,13 @@
             /* get a rendering of each name in the set of names */
+            int gntype;
+            ASN1_STRING *as = NULL;
+
             name = sk_GENERAL_NAME_value(names, j);
-            if (name->type == GEN_DIRNAME) {
+            gntype = name-> type;
+            switch (gntype) {
+            case GEN_DIRNAME:
                 /* we special-case DirName as a tuple of tuples of attributes */
@@ -764,11 +769,61 @@
                     goto fail;
                 }
                 PyTuple_SET_ITEM(t, 1, v);
+                break;
-            } else {
+            case GEN_EMAIL:
+            case GEN_DNS:
+            case GEN_URI:
+                /* GENERAL_NAME_print() doesn't handle NUL bytes in ASN1_string
+                   correctly. */
+                t = PyTuple_New(2);
+                if (t == NULL)
+                    goto fail;
+                switch (gntype) {
+                case GEN_EMAIL:
+                    v = PyUnicode_FromString("email");
+                    as = name->d.rfc822Name;
+                    break;
+                case GEN_DNS:
+                    v = PyUnicode_FromString("DNS");
+                    as = name->d.dNSName;
+                    break;
+                case GEN_URI:
+                    v = PyUnicode_FromString("URI");
+                    as = name->d.uniformResourceIdentifier;
+                    break;
+                }
+                if (v == NULL) {
+                    Py_DECREF(t);
+                    goto fail;
+                }
+                PyTuple_SET_ITEM(t, 0, v);
+                v = PyString_FromStringAndSize((char *)ASN1_STRING_data(as),
+                                               ASN1_STRING_length(as));
+                if (v == NULL) {
+                    Py_DECREF(t);
+                    goto fail;
+                }
+                PyTuple_SET_ITEM(t, 1, v);
+                break;
+            default:
                 /* for everything else, we use the OpenSSL print form */
-
+                switch (gntype) {
+                    /* check for new general name type */
+                    case GEN_OTHERNAME:
+                    case GEN_X400:
+                    case GEN_EDIPARTY:
+                    case GEN_IPADD:
+                    case GEN_RID:
+                        break;
+                    default:
+                        if (PyErr_Warn(PyExc_RuntimeWarning,
+                       "Unknown general name type") == -1) {
+                            goto fail;
+                        }
+                        break;
+                }
                 (void) BIO_reset(biobuf);
                 GENERAL_NAME_print(biobuf, name);
                 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
@@ -794,6 +849,7 @@
                     goto fail;
                 }
                 PyTuple_SET_ITEM(t, 1, v);
+        break;
             }
             /* and add that rendering to the list */
SOURCES/00189-gdb-py-bt-dont-raise-exception-from-eval.patch
New file
@@ -0,0 +1,11 @@
--- Python-2.7.5-orig/Tools/gdb/libpython.py    2013-05-12 03:32:54.000000000 +0000
+++ Python-2.7.5-orig/Tools/gdb/libpython.py    2013-09-15 09:56:25.494000000 +0000
@@ -887,6 +887,8 @@
         newline character'''
         if self.is_optimized_out():
             return '(frame information optimized out)'
+        if self.filename() == '<string>':
+            return '(in an eval block)'
         with open(self.filename(), 'r') as f:
             all_lines = f.readlines()
             # Convert from 1-based current_line_num to 0-based list offset:
SOURCES/00190-gdb-fix-ppc64-failures.patch
New file
@@ -0,0 +1,207 @@
--- Tools/gdb/libpython.py.orig    2013-10-09 10:54:59.894701668 +0200
+++ Tools/gdb/libpython.py    2013-10-09 11:09:30.278703290 +0200
@@ -1194,39 +1194,113 @@
             iter_frame = iter_frame.newer()
         return index
+    # We divide frames into:
+    #   - "python frames":
+    #       - "bytecode frames" i.e. PyEval_EvalFrameEx
+    #       - "other python frames": things that are of interest from a python
+    #         POV, but aren't bytecode (e.g. GC, GIL)
+    #   - everything else
+
+    def is_python_frame(self):
+        '''Is this a PyEval_EvalFrameEx frame, or some other important
+        frame? (see is_other_python_frame for what "important" means in this
+        context)'''
+        if self.is_evalframeex():
+            return True
+        if self.is_other_python_frame():
+            return True
+        return False
+
     def is_evalframeex(self):
-        '''Is this a PyEval_EvalFrameEx frame?'''
-        if self._gdbframe.name() == 'PyEval_EvalFrameEx':
-            '''
-            I believe we also need to filter on the inline
-            struct frame_id.inline_depth, only regarding frames with
-            an inline depth of 0 as actually being this function
-
-            So we reject those with type gdb.INLINE_FRAME
-            '''
-            if self._gdbframe.type() == gdb.NORMAL_FRAME:
-                # We have a PyEval_EvalFrameEx frame:
-                return True
+        if self._gdbframe.function():
+            if self._gdbframe.function().name == 'PyEval_EvalFrameEx':
+                '''
+                I believe we also need to filter on the inline
+                struct frame_id.inline_depth, only regarding frames with
+                an inline depth of 0 as actually being this function
+
+                So we reject those with type gdb.INLINE_FRAME
+                '''
+                if self._gdbframe.type() == gdb.NORMAL_FRAME:
+                    # We have a PyEval_EvalFrameEx frame:
+                    return True
+
+        return False
+
+    def is_other_python_frame(self):
+        '''Is this frame worth displaying in python backtraces?
+        Examples:
+          - waiting on the GIL
+          - garbage-collecting
+          - within a CFunction
+         If it is, return a descriptive string
+         For other frames, return False
+         '''
+        if self.is_waiting_for_gil():
+            return 'Waiting for a lock (e.g. GIL)'
+        elif self.is_gc_collect():
+            return 'Garbage-collecting'
+        else:
+            # Detect invocations of PyCFunction instances:
+            if self._gdbframe.name() == 'PyCFunction_Call':
+                try:
+                    func = self._gdbframe.read_var('func')
+                    # Use the prettyprinter for the func:
+                    return str(func)
+                except RuntimeError:
+                    return 'PyCFunction invocation (unable to read "func")'
+            older = self.older()
+            if older and older._gdbframe.name() == 'call_function':
+                # Within that frame:
+                # 'call_function' contains, amongst other things, a
+                # hand-inlined copy of PyCFunction_Call.
+                #   "func" is the local containing the PyObject* of the
+                # callable instance
+                # Report it, but only if it's a PyCFunction (since otherwise
+                # we'd be reporting an implementation detail of every other
+                # function invocation)
+                try:
+                    func = older._gdbframe.read_var('func')
+                    funcobj = PyObjectPtr.from_pyobject_ptr(func)
+                    if isinstance(funcobj, PyCFunctionObjectPtr):
+                        # Use the prettyprinter for the func:
+                        return str(func)
+                except RuntimeError:
+                    return False
+        # This frame isn't worth reporting:
         return False
+    def is_waiting_for_gil(self):
+        '''Is this frame waiting for a lock?'''
+        framename = self._gdbframe.name()
+        if framename:
+            return 'pthread_cond_timedwait' in framename or \
+                   'PyThread_acquire_lock' in framename
+
+    def is_gc_collect(self):
+        '''Is this frame "collect" within the the garbage-collector?'''
+        return self._gdbframe.name() == 'collect'
+
     def get_pyop(self):
         try:
             f = self._gdbframe.read_var('f')
-            frame = PyFrameObjectPtr.from_pyobject_ptr(f)
-            if not frame.is_optimized_out():
-                return frame
-            # gdb is unable to get the "f" argument of PyEval_EvalFrameEx()
-            # because it was "optimized out". Try to get "f" from the frame
-            # of the caller, PyEval_EvalCodeEx().
-            orig_frame = frame
-            caller = self._gdbframe.older()
-            if caller:
-                f = caller.read_var('f')
-                frame = PyFrameObjectPtr.from_pyobject_ptr(f)
-                if not frame.is_optimized_out():
-                    return frame
-            return orig_frame
+            obj = PyFrameObjectPtr.from_pyobject_ptr(f)
+            if isinstance(obj, PyFrameObjectPtr):
+                return obj
+            else:
+                return None
+        except ValueError:
+            return None
+
+    def get_py_co(self):
+        try:
+            co = self._gdbframe.read_var('co')
+            obj = PyCodeObjectPtr.from_pyobject_ptr(co)
+            if isinstance(obj, PyCodeObjectPtr):
+                return obj
+            else:
+                return None
         except ValueError:
             return None
@@ -1239,8 +1313,22 @@
     @classmethod
     def get_selected_python_frame(cls):
-        '''Try to obtain the Frame for the python code in the selected frame,
-        or None'''
+        '''Try to obtain the Frame for the python-related code in the selected
+        frame, or None'''
+        frame = cls.get_selected_frame()
+
+        while frame:
+            if frame.is_python_frame():
+                return frame
+            frame = frame.older()
+
+        # Not found:
+        return None
+
+    @classmethod
+    def get_selected_bytecode_frame(cls):
+        '''Try to obtain the Frame for the python bytecode interpreter in the
+        selected GDB frame, or None'''
         frame = cls.get_selected_frame()
         while frame:
@@ -1265,7 +1353,11 @@
             else:
                 sys.stdout.write('#%i (unable to read python frame information)\n' % self.get_index())
         else:
-            sys.stdout.write('#%i\n' % self.get_index())
+            info = self.is_other_python_frame()
+            if info:
+                sys.stdout.write('#%i %s\n' % (self.get_index(), info))
+            else:
+                sys.stdout.write('#%i\n' % self.get_index())
 class PyList(gdb.Command):
     '''List the current Python source code, if any
@@ -1301,7 +1393,7 @@
         if m:
             start, end = map(int, m.groups())
-        frame = Frame.get_selected_python_frame()
+        frame = Frame.get_selected_bytecode_frame()
         if not frame:
             print 'Unable to locate python frame'
             return
@@ -1353,7 +1445,7 @@
         if not iter_frame:
             break
-        if iter_frame.is_evalframeex():
+        if iter_frame.is_python_frame():
             # Result:
             if iter_frame.select():
                 iter_frame.print_summary()
@@ -1407,7 +1499,7 @@
     def invoke(self, args, from_tty):
         frame = Frame.get_selected_python_frame()
         while frame:
-            if frame.is_evalframeex():
+            if frame.is_python_frame():
                 frame.print_summary()
             frame = frame.older()
SOURCES/00191-add-RPATH-to-elementtree.patch
New file
@@ -0,0 +1,21 @@
diff -up Python-2.7.5/setup.py.orig Python-2.7.5/setup.py
--- Python-2.7.5/setup.py.orig    2013-11-07 01:36:18.853604232 +0100
+++ Python-2.7.5/setup.py    2013-11-07 01:39:22.163305821 +0100
@@ -1483,6 +1483,9 @@ class PyBuildExt(build_ext):
         # Fredrik Lundh's cElementTree module.  Note that this also
         # uses expat (via the CAPI hook in pyexpat).
+        # Add an explicit RPATH to _elementtree.so (rhbz#1019345)
+        EXPAT_RPATH = '/usr/lib64' if sys.maxint == 0x7fffffffffffffff else '/usr/lib'
+
         if os.path.isfile(os.path.join(srcdir, 'Modules', '_elementtree.c')):
             define_macros.append(('USE_PYEXPAT_CAPI', None))
             exts.append(Extension('_elementtree',
@@ -1492,6 +1495,7 @@ class PyBuildExt(build_ext):
                                   sources = ['_elementtree.c'],
                                   depends = ['pyexpat.c'] + expat_sources +
                                       expat_depends,
+                                  extra_link_args = ['-Wl,-rpath,%s' % EXPAT_RPATH]
                                   ))
         else:
             missing.append('_elementtree')
SOURCES/05000-autotool-intermediates.patch
New file