code:
The memory statistics code leads to segfaults during initialization (on
machines with InfiniPath networking):

  (gdb) bt full
  #0  ips_ptl_init (ep=0x1fc6af8, ptl=0x1fc6f88, ctl=0x1fc6d78) at ptl.c:224
	  err = PSM_OK
	  num_of_send_bufs = 1024
	  num_of_send_desc = 4096
	  imm_size = 128
	  context = 0x1fc6b70
	  user_info = 0x1fc6b90
	  enable_shcontexts = 0
	  current_count = <optimized out>
  #1  0x00007fb2aa672abf in __psm_ep_open_internal (
      unique_job_key=unique_job_key@entry=0x7ffed1ee5800 "<\207\020#5\271\267\200\354x\242e8\364zo",
      devid_enabled=devid_enabled@entry=0x7ffed1ee5724, opts_i=opts_i@entry=0x7ffed1ee5810, mq=<optimized out>,
      epo=epo@entry=0x7ffed1ee5710, epido=epido@entry=0x7ffed1ee5708) at psm_ep.c:929
	  ep = 0x1fc6af8
	  num_units = 1
	  len = <optimized out>
	  err = <optimized out>
	  epaddr = 0x1e9dd78
	  buf = "miriel044:2.0.", '\000' <repeats 113 times>
	  p = <optimized out>
	  e = <optimized out>
	  old_cpuaff = 0x0
	  old_unit = 0x0
	  yield_cnt = {e_void = 0xfa, e_str = 0xfa <error: Cannot access memory at address 0xfa>, e_int = 250,
	    e_uint = 250, e_long = 250, e_ulong = 250, e_ulonglong = 250}
	  no_cpuaff = {e_void = 0x0, e_str = 0x0, e_int = 0, e_uint = 0, e_long = 0, e_ulong = 0, e_ulonglong = 0}
	  env_unit_id = {e_void = 0xffffffffffffffff,
	    e_str = 0xffffffffffffffff <error: Cannot access memory at address 0xffffffffffffffff>, e_int = -1,
	    e_uint = 4294967295, e_long = -1, e_ulong = 18446744073709551615, e_ulonglong = 18446744073709551615}
	  env_port_id = {e_void = 0x0, e_str = 0x0, e_int = 0, e_uint = 0, e_long = 0, e_ulong = 0, e_ulonglong = 0}
	  env_sl = {e_void = 0x0, e_str = 0x0, e_int = 0, e_uint = 0, e_long = 0, e_ulong = 0, e_ulonglong = 0}
	  ptl_sizes = <optimized out>
	  default_cpuaff = <optimized out>
	  opts = {timeout = 180000000000, unit = -1, affinity = 0, shm_mbytes = 10, sendbufs_num = 1024,
	    network_pkey = 65535, port = 0, outsl = 0, service_id = 1152940698815692800,
	    path_res_type = PSM_PATH_RES_NONE, senddesc_num = 4096, imm_size = 128}
	  amsh_ptl = 0x1fc6e48
	  ips_ptl = 0x1fc6f88
	  self_ptl = 0x1fc99c8
	  i = 3

It looks like ptl.c:24 is writing past the region that was malloc'd.

Turning stats off solves the problem.

diff --git a/psm_utils.c b/psm_utils.c
index c8651fe..5514921 100644
--- a/psm_utils.c
+++ b/psm_utils.c
@@ -1058,7 +1058,7 @@ psmi_log_memstats(psmi_memtype_t type, int64_t nbytes)
     return;
 }

-#define psmi_stats_mask PSMI_STATSTYPE_MEMORY
+#define psmi_stats_mask 0

 #ifdef malloc
 #undef malloc


code:
Add missing flags.

--- psm-3.3/ipath/Makefile~	1970-01-01 01:00:00.000000000 +0100
+++ psm-3.3/ipath/Makefile	2017-10-22 15:10:10.269177711 +0100
@@ -73,7 +73,7 @@
 ${TARGLIB}.so.${MAJOR}.${MINOR}: ${${TARGLIB}-objs}
 	date +'static __attribute__ ((unused)) char __psc_infinipath_revision[] ="$$""Date: %F %R ${rpm_extra_description}InfiniPath $$";' > _revision.c
 	$(CC) -c $(BASECFLAGS) $(INCLUDES) _revision.c -o _revision.o
-	$(CC) -o $@ -Wl,-soname=${TARGLIB}.so.${MAJOR} -shared \
+	$(CC) -o $@ -Wl,-soname=${TARGLIB}.so.${MAJOR} $(LDFLAGS) -shared \
 		-Wl,--unique='*fastpath*' \
 		${${TARGLIB}-objs} _revision.o $(LDFLAGS) $(if $(MIC:0=),$(SCIF_LINK_FLAGS))

repo_name: maximed/guix

license: mit


code:
From <https://github.com/bmwiedemann/psm/commit/98acae1a6f2c9b2e6014eac4070a817c9d0fd8a2>.

From 98acae1a6f2c9b2e6014eac4070a817c9d0fd8a2 Mon Sep 17 00:00:00 2001
From: "Bernhard M. Wiedemann" <bwiedemann@suse.de>
Date: Sun, 23 Jul 2017 07:02:28 +0200
Subject: [PATCH] Allow to override build date

in order to make builds reproducible.
See https://reproducible-builds.org/ for why this is good
and https://reproducible-builds.org/specs/source-date-epoch/
for the definition of this variable.

Also uses UTC to be independent of timezone settings.
---
 Makefile       | 2 +-
 ipath/Makefile | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

diff --git a/Makefile b/Makefile
index d79c4bd..99406ef 100644
--- a/Makefile
+++ b/Makefile
@@ -270,7 +270,7 @@ ${TARGLIB}.so.${MAJOR}: ${TARGLIB}.so.${MAJOR}.${MINOR}
 # file around.  Generate it such that the ident command can find it
 # and strings -a | grep InfiniPath does a reasonable job as well.
 ${TARGLIB}.so.${MAJOR}.${MINOR}: ${${TARGLIB}-objs}
-	date +'char psmi_infinipath_revision[] ="$$""Date: %F %R ${rpm_extra_description}InfiniPath $$";' > ${lib_build_dir}/_revision.c
+	date -u -d@$${SOURCE_DATE_EPOCH:-$$(date +%s)} +'char psmi_infinipath_revision[] ="$$""Date: %F %R ${rpm_extra_description}InfiniPath $$";' > ${lib_build_dir}/_revision.c
 	$(CC) -c $(BASECFLAGS) $(INCLUDES) _revision.c -o _revision.o
 	$(CC) $(LDFLAGS) -o $@ -Wl,-soname=${TARGLIB}.so.${MAJOR} -shared -Wl,--unique='*fastpath*' \
 		${${TARGLIB}-objs} _revision.o -L$(build_dir)/ipath $(LDLIBS)
diff --git a/ipath/Makefile b/ipath/Makefile
index 8c2cc6e..73abd6f 100644
--- a/ipath/Makefile
+++ b/ipath/Makefile
@@ -70,7 +70,7 @@ ${TARGLIB}.so.${MAJOR}: ${TARGLIB}.so.${MAJOR}.${MINOR}
 # file around.  Generate it such that the ident command can find it
 # and strings -a | grep InfiniPath does a reasonable job as well.
 ${TARGLIB}.so.${MAJOR}.${MINOR}: ${${TARGLIB}-objs}
-	date +'static __attribute__ ((unused)) char __psc_infinipath_revision[] ="$$""Date: %F %R ${rpm_extra_description}InfiniPath $$";' > _revision.c
+	date -u -d@$${SOURCE_DATE_EPOCH:-$$(date +%s)} +'static __attribute__ ((unused)) char __psc_infinipath_revision[] ="$$""Date: %F %R ${rpm_extra_description}InfiniPath $$";' > _revision.c
 	$(CC) -c $(BASECFLAGS) $(INCLUDES) _revision.c -o _revision.o
 	$(CC) -o $@ -Wl,-soname=${TARGLIB}.so.${MAJOR} -shared \
 		-Wl,--unique='*fastpath*' \


code:
Avoid signed overflow during mult-s16-test which intermittently
failed.

Patch by Mark H Weaver <mhw@netris.org>.

--- pulseaudio-5.0/src/tests/mult-s16-test.c.orig	2014-01-23 13:57:55.000000000 -0500
+++ pulseaudio-5.0/src/tests/mult-s16-test.c	2014-10-24 03:13:46.464661815 -0400
@@ -55,7 +55,7 @@
 START_TEST (mult_s16_test) {
     int16_t samples[SAMPLES];
     int32_t volumes[SAMPLES];
-    int32_t sum1 = 0, sum2 = 0;
+    uint32_t sum1 = 0, sum2 = 0;
     int i;

     pa_random(samples, sizeof(samples));


code:
Increase the timeout on 'cpu-mix-test' to accommodate slower machines.

--- pulseaudio-6.0/src/tests/cpu-mix-test.c.ORIG	2015-02-12 09:10:35.000000000 -0500
+++ pulseaudio-6.0/src/tests/cpu-mix-test.c	2015-03-31 13:45:05.316878322 -0400
@@ -212,7 +212,7 @@
 #if defined (__arm__) && defined (__linux__) && defined (HAVE_NEON)
     tcase_add_test(tc, mix_neon_test);
 #endif
-    tcase_set_timeout(tc, 120);
+    tcase_set_timeout(tc, 240);
     suite_add_tcase(s, tc);

     sr = srunner_create(s);


code:
https://sigrok.org/gitweb/?p=pulseview.git;a=patch;h=ae726b70a7ada9a4be5808e00f0c951318479684

From ae726b70a7ada9a4be5808e00f0c951318479684 Mon Sep 17 00:00:00 2001
From: Valentin Ochs <a@0au.de>
Date: Sat, 20 Jun 2020 16:01:27 +0200
Subject: [PATCH] Replace obsolete/deprecated Qt methods

---
 pv/subwindows/decoder_selector/subwindow.cpp |  2 +-
 pv/util.cpp                                  | 21 ++++++++++++++++++--
 pv/util.hpp                                  | 10 ++++++++++
 pv/views/trace/decodetrace.cpp               |  3 ++-
 pv/views/trace/ruler.cpp                     |  2 +-
 pv/widgets/timestampspinbox.cpp              |  2 +-
 6 files changed, 34 insertions(+), 6 deletions(-)

diff --git a/pv/subwindows/decoder_selector/subwindow.cpp b/pv/subwindows/decoder_selector/subwindow.cpp
index 94ed6f4b..2c65dcf2 100644
--- a/pv/subwindows/decoder_selector/subwindow.cpp
+++ b/pv/subwindows/decoder_selector/subwindow.cpp
@@ -185,7 +185,7 @@ QToolBar* SubWindow::create_toolbar(QWidget *parent) const
 int SubWindow::minimum_width() const
 {
 	QFontMetrics m(info_label_body_->font());
-	const int label_width = m.width(QString(tr(initial_notice)));
+	const int label_width = util::text_width(m, tr(initial_notice));

 	return label_width + min_width_margin;
 }
diff --git a/pv/util.cpp b/pv/util.cpp
index 897254e1..dfb8c72b 100644
--- a/pv/util.cpp
+++ b/pv/util.cpp
@@ -143,7 +143,7 @@ QString format_time_si(const Timestamp& v, SIPrefix prefix,
 	QString s;
 	QTextStream ts(&s);
 	if (sign && !v.is_zero())
-		ts << forcesign;
+		ts.setNumberFlags(ts.numberFlags() | QTextStream::ForceSign);
 	ts << qSetRealNumberPrecision(precision) << (v * multiplier);
 	ts << ' ' << prefix << unit;

@@ -169,7 +169,7 @@ QString format_value_si(double v, SIPrefix prefix, unsigned precision,
 	QString s;
 	QTextStream ts(&s);
 	if (sign && (v != 0))
-		ts << forcesign;
+		ts.setNumberFlags(ts.numberFlags() | QTextStream::ForceSign);
 	ts.setRealNumberNotation(QTextStream::FixedNotation);
 	ts.setRealNumberPrecision(precision);
 	ts << (v * multiplier) << ' ' << prefix << unit;
@@ -279,5 +279,22 @@ vector<string> split_string(string text, string separator)
 	return result;
 }

+/**
+ * Return the width of a string in a given font.
+ *
+ * @param[in] metric metrics of the font
+ * @param[in] string the string whose width should be determined
+ *
+ * @return width of the string in pixels
+ */
+std::streamsize text_width(const QFontMetrics &metric, const QString &string)
+{
+#if QT_VERSION >= QT_VERSION_CHECK(5, 11, 0)
+	return metric.horizontalAdvance(string);
+#else
+	return metric.width(string);
+#endif
+}
+
 } // namespace util
 } // namespace pv
diff --git a/pv/util.hpp b/pv/util.hpp
index fab29a14..49ae04b2 100644
--- a/pv/util.hpp
+++ b/pv/util.hpp
@@ -30,6 +30,7 @@

 #include <QMetaType>
 #include <QString>
+#include <QFontMetrics>

 using std::string;
 using std::vector;
@@ -143,6 +144,15 @@ QString format_time_minutes(const Timestamp& t, signed precision = 0,

 vector<string> split_string(string text, string separator);

+/**
+ * Return the width of a string in a given font.
+ * @param[in] metric metrics of the font
+ * @param[in] string the string whose width should be determined
+ *
+ * @return width of the string in pixels
+ */
+std::streamsize text_width(const QFontMetrics &metric, const QString &string);
+
 } // namespace util
 } // namespace pv

diff --git a/pv/views/trace/decodetrace.cpp b/pv/views/trace/decodetrace.cpp
index 67c9b1c4..93c7c5a9 100644
--- a/pv/views/trace/decodetrace.cpp
+++ b/pv/views/trace/decodetrace.cpp
@@ -161,7 +161,8 @@ DecodeTrace::DecodeTrace(pv::Session &session,

 	// Determine shortest string we want to see displayed in full
 	QFontMetrics m(QApplication::font());
-	min_useful_label_width_ = m.width("XX"); // e.g. two hex characters
+	// e.g. two hex characters
+	min_useful_label_width_ = util::text_width(m, "XX");

 	default_row_height_ = (ViewItemPaintParams::text_height() * 6) / 4;
 	annotation_height_ = (ViewItemPaintParams::text_height() * 5) / 4;
diff --git a/pv/views/trace/ruler.cpp b/pv/views/trace/ruler.cpp
index 555794fc..83ffed28 100644
--- a/pv/views/trace/ruler.cpp
+++ b/pv/views/trace/ruler.cpp
@@ -283,7 +283,7 @@ void Ruler::paintEvent(QPaintEvent*)
 		const int rightedge = width();
 		const int x_tick = tick.first;
 		if ((x_tick > leftedge) && (x_tick < rightedge)) {
-			const int x_left_bound = QFontMetrics(font()).width(tick.second) / 2;
+			const int x_left_bound = util::text_width(QFontMetrics(font()), tick.second) / 2;
 			const int x_right_bound = rightedge - x_left_bound;
 			const int x_legend = min(max(x_tick, x_left_bound), x_right_bound);
 			p.drawText(x_legend, ValueMargin, 0, text_height,
diff --git a/pv/widgets/timestampspinbox.cpp b/pv/widgets/timestampspinbox.cpp
index fea8175e..01424a5b 100644
--- a/pv/widgets/timestampspinbox.cpp
+++ b/pv/widgets/timestampspinbox.cpp
@@ -76,7 +76,7 @@ QSize TimestampSpinBox::minimumSizeHint() const
 {
 	const QFontMetrics fm(fontMetrics());
 	const int l = round(value_).str().size() + precision_ + 10;
-	const int w = fm.width(QString(l, '0'));
+	const int w = util::text_width(fm, QString(l, '0'));
 	const int h = lineEdit()->minimumSizeHint().height();
 	return QSize(w, h);
 }
--
2.24.0.rc2


code:
Allow the purescript dependencies to better match the available packages in
Guix.

--- purescript-0.13.8/purescript.cabal
+++ purescript-0.13.8/purescript.cabal.orig
@@ -1091 +1091 @@ library
-        Glob ==0.9.*,
+        Glob ==0.10.*,
@@ -1095 +1095 @@ library
-        ansi-terminal >=0.7.1 && <0.9,
+        ansi-terminal ==0.9.*,
@@ -1105 +1105 @@ library
-        clock <0.8,
+        clock ==0.8.*,
@@ -1173 +1173 @@ executable purs
-        Glob ==0.9.*,
+        Glob ==0.10.*,
@@ -1177 +1177 @@ executable purs
-        ansi-terminal >=0.7.1 && <0.9,
+        ansi-terminal ==0.9.*,
@@ -1188 +1188 @@ executable purs
-        clock <0.8,
+        clock ==0.8.*,
@@ -1209 +1209 @@ executable purs
-        network >=3.0.1.1 && <3.1,
+        network >=2.8 && <3.1,
@@ -1288 +1288 @@ test-suite tests
-        Glob ==0.9.*,
+        Glob ==0.10.*,
@@ -1293 +1293 @@ test-suite tests
-        ansi-terminal >=0.7.1 && <0.9,
+        ansi-terminal ==0.9.*,
@@ -1303 +1303 @@ test-suite tests
-        clock <0.8,
+        clock ==0.8.*,
@@ -1315,2 +1315,2 @@ test-suite tests
-        hspec <2.7,
-        hspec-discover <2.7,
+        hspec ==2.7.*,
+        hspec-discover ==2.7.*,


code:
In case of 'AttributeError', 'value' is None, so do not try to
access it.
Submitted upstream.

--- pybugz-0.6.11/bugz.py	2006-09-02 14:35:37.000000000 +0200
+++ pybugz-0.6.11/bugz.py	2014-05-05 16:02:20.000000000 +0200
@@ -1249,9 +1254,9 @@ class PrettyBugz(Bugz):
         for field, name in FIELDS + MORE_FIELDS:
             try:
                 value = result.find('//%s' % field).text
+                print '%-12s: %s' % (name, value.encode(self.enc))
             except AttributeError:
                 continue
-            print '%-12s: %s' % (name, value.encode(self.enc))

         # Print out the cc'ed people
         cced = result.findall('.//cc')


code:
Gracefully deal with 'stty size' failures.
Submitted upstream.

--- pybugz-0.6.11/bugz.py	2006-09-02 14:35:37.000000000 +0200
+++ pybugz-0.6.11/bugz.py	2014-05-05 15:17:03.000000000 +0200
@@ -288,7 +288,12 @@ def get_cols():
     stty = which('stty')
     if stty:
         row_cols = commands.getoutput("%s size" % stty)
-        rows, cols = map(int, row_cols.split())
+        try:
+            rows, cols = map(int, row_cols.split())
+        except:
+            # In some cases 'stty size' will just fail with
+            # "Inappropriate ioctl for device".
+            cols = DEFAULT_NUM_COLS
         return cols
     else:
         return DEFAULT_NUM_COLS


code:
These tests require a gpg agent to run, and are difficult to get to work right
in Guix's environment.  For more details, see:
  https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=713074
  https://bugs.launchpad.net/pygpgme/+bug/999949

--- pygpgme-0.3/tests/test_encrypt_decrypt.py	2012-02-28 19:10:28.000000000 -0800
+++ pygpgme-0.3/tests/test_encrypt_decrypt.py	2016-02-05 10:21:58.966685384 -0800
@@ -125,7 +125,7 @@
         ctx.decrypt(ciphertext, plaintext)
         self.assertEqual(plaintext.getvalue(), b'Hello World\n')

-    def test_encrypt_symmetric(self):
+    def skip_test_encrypt_symmetric(self):
         plaintext = BytesIO(b'Hello World\n')
         ciphertext = BytesIO()
         def passphrase(uid_hint, passphrase_info, prev_was_bad, fd):

--- pygpgme-0.3/tests/test_passphrase.py	2012-02-28 19:04:17.000000000 -0800
+++ pygpgme-0.3/tests/test_passphrase.py	2016-02-05 10:21:47.990630956 -0800
@@ -30,7 +30,7 @@

     import_keys = ['passphrase.pub', 'passphrase.sec']

-    def test_sign_without_passphrase_cb(self):
+    def skip_test_sign_without_passphrase_cb(self):
         ctx = gpgme.Context()
         key = ctx.get_key('EFB052B4230BBBC51914BCBB54DCBBC8DBFB9EB3')
         ctx.signers = [key]
@@ -51,7 +51,7 @@
         self.prev_was_bad = prev_was_bad
         os.write(fd, b'test\n')

-    def test_sign_with_passphrase_cb(self):
+    def skip_test_sign_with_passphrase_cb(self):
         ctx = gpgme.Context()
         key = ctx.get_key('EFB052B4230BBBC51914BCBB54DCBBC8DBFB9EB3')
         ctx.signers = [key]


code:
Fix a few testcases. Adapted from python-3-fix-tests.patch.

diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/ctypes/test/test_callbacks.py pypy3.6-v7.3.1-src/lib-python/3/ctypes/test/test_callbacks.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/ctypes/test/test_callbacks.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/ctypes/test/test_callbacks.py	2020-05-21 14:19:14.827288853 +0200
@@ -4,6 +4,7 @@
 from ctypes import *
 from ctypes.test import need_symbol
 import _ctypes_test
+import platform

 class Callbacks(unittest.TestCase):
     functype = CFUNCTYPE
@@ -178,6 +179,8 @@

         self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)

+    @unittest.skipIf(platform.machine() in ['mips64'],
+                     "This test fails on this platform")
     def test_issue_8959_a(self):
         from ctypes.util import find_library
         libc_path = find_library("c")
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/ctypes/test/test_libc.py pypy3.6-v7.3.1-src/lib-python/3/ctypes/test/test_libc.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/ctypes/test/test_libc.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/ctypes/test/test_libc.py	2020-05-21 14:19:14.827288853 +0200
@@ -2,6 +2,7 @@

 from ctypes import *
 import _ctypes_test
+import platform

 lib = CDLL(_ctypes_test.__file__)

@@ -17,6 +18,8 @@
         import math
         self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0))

+    @unittest.skipIf(platform.machine() in ['mips64'],
+                     "This test fails on this platform")
     def test_qsort(self):
         comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char))
         lib.my_qsort.argtypes = c_void_p, c_size_t, c_size_t, comparefunc
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/distutils/tests/test_archive_util.py pypy3.6-v7.3.1-src/lib-python/3/distutils/tests/test_archive_util.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/distutils/tests/test_archive_util.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/distutils/tests/test_archive_util.py	2020-05-21 14:19:14.827288853 +0200
@@ -333,6 +333,7 @@
         self.assertEqual(os.path.basename(res), 'archive.tar.xz')
         self.assertEqual(self._tarinfo(res), self._created_files)

+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -362,6 +363,7 @@

     @unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_tarfile_root_owner(self):
         tmpdir =  self._create_files()
         base_name = os.path.join(self.mkdtemp(), 'archive')
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/distutils/tests/test_sdist.py pypy3.6-v7.3.1-src/lib-python/3/distutils/tests/test_sdist.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/distutils/tests/test_sdist.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/distutils/tests/test_sdist.py	2020-05-21 14:19:14.827288853 +0200
@@ -443,6 +443,7 @@
                      "The tar command is not found")
     @unittest.skipIf(find_executable('gzip') is None,
                      "The gzip command is not found")
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_distribution_owner_group(self):
         # now building a sdist
         dist, cmd = self.get_cmd()
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_asyncio/test_base_events.py pypy3.6-v7.3.1-src/lib-python/3/test/test_asyncio/test_base_events.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_asyncio/test_base_events.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_asyncio/test_base_events.py	2020-05-21 14:19:14.827288853 +0200
@@ -1296,6 +1296,8 @@
         self._test_create_connection_ip_addr(m_socket, False)

     @patch_socket
+    @unittest.skipUnless(support.is_resource_enabled('network'),
+                         'network is not enabled')
     def test_create_connection_service_name(self, m_socket):
         m_socket.getaddrinfo = socket.getaddrinfo
         sock = m_socket.socket.return_value
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_generators.py pypy3.6-v7.3.1-src/lib-python/3/test/test_generators.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_generators.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_generators.py	2020-05-21 14:19:14.827288853 +0200
@@ -35,6 +35,7 @@
         else:
             return "FAILED"

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment')
     def test_raise_and_yield_from(self):
         gen = self.generator1()
         gen.send(None)
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/_test_multiprocessing.py pypy3.6-v7.3.1-src/lib-python/3/test/_test_multiprocessing.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/_test_multiprocessing.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/_test_multiprocessing.py	2020-05-21 14:19:14.827288853 +0200
@@ -1212,6 +1212,7 @@
         if pid is not None:
             os.kill(pid, signal.SIGINT)

+    @unittest.skipIf(True, "This fails for unknown reasons on Guix")
     def test_wait_result(self):
         if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
             pid = os.getpid()
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_normalization.py pypy3.6-v7.3.1-src/lib-python/3/test/test_normalization.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_normalization.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_normalization.py	2020-05-21 14:19:14.827288853 +0200
@@ -2,6 +2,7 @@
 import unittest

 from http.client import HTTPException
+from urllib.error import URLError
 import sys
 from unicodedata import normalize, unidata_version

@@ -43,6 +44,8 @@
         except PermissionError:
             self.skipTest(f"Permission error when downloading {TESTDATAURL} "
                           f"into the test data directory")
+        except URLError:
+            self.skipTest("DNS lookups are not enabled.")
         except (OSError, HTTPException):
             self.fail(f"Could not retrieve {TESTDATAURL}")

diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_pathlib.py pypy3.6-v7.3.1-src/lib-python/3/test/test_pathlib.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_pathlib.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_pathlib.py	2020-05-21 14:19:14.827288853 +0200
@@ -2130,8 +2130,7 @@
         self.assertEqual(given, expect)
         self.assertEqual(set(p.rglob("FILEd*")), set())

-    @unittest.skipUnless(hasattr(pwd, 'getpwall'),
-                         'pwd module does not expose getpwall()')
+    @unittest.skipIf(True, "Guix builder home is '/' which causes trouble for these tests")
     def test_expanduser(self):
         P = self.cls
         support.import_module('pwd')
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_pdb.py pypy3.6-v7.3.1-src/lib-python/3/test/test_pdb.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_pdb.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_pdb.py	2020-05-21 14:20:24.377203281 +0200
@@ -1136,11 +1136,11 @@
     > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
     -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
     (Pdb) continue
-    pdb 1: <built-in function default_int_handler>
+    pdb 1: Handlers.SIG_IGN
     > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
     -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
     (Pdb) continue
-    pdb 2: <built-in function default_int_handler>
+    pdb 2: Handlers.SIG_IGN
     """

 class PdbTestCase(unittest.TestCase):
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_regrtest.py pypy3.6-v7.3.1-src/lib-python/3/test/test_regrtest.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_regrtest.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_regrtest.py	2020-05-21 14:19:14.827288853 +0200
@@ -766,6 +766,7 @@
         output = self.run_tests('--fromfile', filename)
         self.check_executed_tests(output, tests)

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment.')
     def test_interrupted(self):
         code = TEST_INTERRUPTED
         test = self.create_test('sigint', code=code)
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_resource.py pypy3.6-v7.3.1-src/lib-python/3/test/test_resource.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_resource.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_resource.py	2020-05-21 14:19:14.827288853 +0200
@@ -146,6 +146,7 @@

     @unittest.skipUnless(hasattr(resource, 'prlimit'), 'no prlimit')
     @support.requires_linux_version(2, 6, 36)
+    @unittest.skipIf(True, "Bug: the PermissionError is not raised")
     def test_prlimit(self):
         self.assertRaises(TypeError, resource.prlimit)
         self.assertRaises(ProcessLookupError, resource.prlimit,
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_shutil.py pypy3.6-v7.3.1-src/lib-python/3/test/test_shutil.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_shutil.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_shutil.py	2020-05-21 14:19:14.827288853 +0200
@@ -1138,6 +1138,7 @@
         self.assertRaises(ValueError, make_archive, base_name, 'xxx')

     @support.requires_zlib
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -1166,6 +1167,7 @@

     @support.requires_zlib
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
     def test_tarfile_root_owner(self):
         root_dir, base_dir = self._create_files()
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_socket.py pypy3.6-v7.3.1-src/lib-python/3/test/test_socket.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_socket.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_socket.py	2020-05-21 14:19:14.827288853 +0200
@@ -815,6 +815,8 @@
         if not fqhn in all_host_names:
             self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))

+    @unittest.skipUnless(support.is_resource_enabled('network'),
+                         'network is not enabled')
     def test_host_resolution(self):
         for addr in [support.HOST, '10.0.0.1', '255.255.255.255']:
             self.assertEqual(socket.gethostbyname(addr), addr)
@@ -934,6 +936,8 @@
             self.assertRaises(OverflowError, socket.htonl, k)
             self.assertRaises(OverflowError, socket.htons, k)

+    @unittest.skipUnless(os.path.exists("/etc/services"),
+                         "getservbyname uses /etc/services, which is not in the chroot")
     def testGetServBy(self):
         eq = self.assertEqual
         # Find one service that exists, then check all the related interfaces.
@@ -1278,6 +1282,8 @@
             raise
         self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None)

+    @unittest.skipUnless(os.path.exists("/etc/gai.conf"),
+                         "getaddrinfo() will fail")
     def testGetaddrinfo(self):
         try:
             socket.getaddrinfo('localhost', 80)
@@ -1357,6 +1363,8 @@
         # only IP addresses are allowed
         self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)

+    @unittest.skipUnless(os.path.exists("/etc/gai.conf"),
+                         "getaddrinfo() will fail")
     @unittest.skipUnless(support.is_resource_enabled('network'),
                          'network is not enabled')
     def test_idna(self):
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_spwd.py pypy3.6-v7.3.1-src/lib-python/3/test/test_spwd.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_spwd.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_spwd.py	2020-05-21 14:19:14.827288853 +0200
@@ -5,8 +5,7 @@
 spwd = support.import_module('spwd')

-@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
-                     'root privileges required')
+@unittest.skipUnless(os.path.exists("/etc/shadow"), 'spwd tests require /etc/shadow')
 class TestSpwdRoot(unittest.TestCase):

     def test_getspall(self):
@@ -56,8 +55,7 @@
             self.assertRaises(TypeError, spwd.getspnam, bytes_name)

-@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() != 0,
-                     'non-root user required')
+@unittest.skipUnless(os.path.exists("/etc/shadow"), 'spwd tests require /etc/shadow')
 class TestSpwdNonRoot(unittest.TestCase):

     def test_getspnam_exception(self):
diff -Naur pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_tarfile.py pypy3.6-v7.3.1-src/lib-python/3/test/test_tarfile.py
--- pypy3.6-v7.3.1-src.orig/lib-python/3/test/test_tarfile.py	1970-01-01 01:00:01.000000000 +0100
+++ pypy3.6-v7.3.1-src/lib-python/3/test/test_tarfile.py	2020-05-21 14:19:14.827288853 +0200
@@ -2491,9 +2491,12 @@
         import pwd, grp
     except ImportError:
         return False
-    if pwd.getpwuid(0)[0] != 'root':
-        return False
-    if grp.getgrgid(0)[0] != 'root':
+    try:
+        if pwd.getpwuid(0)[0] != 'root':
+            return False
+        if grp.getgrgid(0)[0] != 'root':
+            return False
+    except KeyError:
         return False
     return True


code:
Have configure.py modify internal variables depending on the --qml-plugindir
configure option.
diff -u PyQt-gpl-5.4.alt/configure.py PyQt-gpl-5.4/configure.py
--- PyQt-gpl-5.4.alt/configure.py	2015-01-25 17:27:50.000000000 +0100
+++ PyQt-gpl-5.4/configure.py	2015-01-25 17:56:41.000000000 +0100
@@ -904,6 +904,9 @@
         if opts.pyuicinterpreter is not None:
             self.pyuic_interpreter = opts.pyuicinterpreter

+        if opts.qmlplugindir is not None:
+            self.qml_plugin_dir = opts.qmlplugindir
+
         if opts.qsciapidir is not None:
             self.qsci_api_dir = opts.qsciapidir


code:
Always provide the same date and time in 'Py_GetBuildInfo'.
This is the information shown at the REPL and in 'sys.version'.
We cannot pass it in CPPFLAGS due to whitespace in the DATE string.

--- a/Modules/getbuildinfo.c
+++ b/Modules/getbuildinfo.c
@@ -4,6 +4,10 @@
 #include <stdio.h>
 #endif

+/* Deterministic date and time.  */
+#define DATE "Jan  1 1970"
+#define TIME "00:00:01"
+
 #ifndef DATE
 #ifdef __DATE__
 #define DATE __DATE__


code:
Fix CVE-2021-3177 for Python 2.7:

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3177

Patch copied from Debian:

https://salsa.debian.org/cpython-team/python2/-/blob/e54f3303884f1362f3311ec36f070b40603dd76e/debian/patches/CVE-2021-3177.diff

bpo-42938: Replace snprintf with Python unicode formatting in ctypes param reprs.
--- a/Lib/ctypes/test/test_parameters.py
+++ b/Lib/ctypes/test/test_parameters.py
@@ -206,6 +206,49 @@ class SimpleTypesTestCase(unittest.TestC
         with self.assertRaises(ZeroDivisionError):
             WorseStruct().__setstate__({}, b'foo')

+    def test_parameter_repr(self):
+        from ctypes import (
+            c_bool,
+            c_char,
+            c_wchar,
+            c_byte,
+            c_ubyte,
+            c_short,
+            c_ushort,
+            c_int,
+            c_uint,
+            c_long,
+            c_ulong,
+            c_longlong,
+            c_ulonglong,
+            c_float,
+            c_double,
+            c_longdouble,
+            c_char_p,
+            c_wchar_p,
+            c_void_p,
+        )
+        self.assertRegexpMatches(repr(c_bool.from_param(True)), r"^<cparam '\?' at 0x[A-Fa-f0-9]+>$")
+        self.assertEqual(repr(c_char.from_param('a')), "<cparam 'c' (a)>")
+        self.assertRegexpMatches(repr(c_wchar.from_param('a')), r"^<cparam 'u' at 0x[A-Fa-f0-9]+>$")
+        self.assertEqual(repr(c_byte.from_param(98)), "<cparam 'b' (98)>")
+        self.assertEqual(repr(c_ubyte.from_param(98)), "<cparam 'B' (98)>")
+        self.assertEqual(repr(c_short.from_param(511)), "<cparam 'h' (511)>")
+        self.assertEqual(repr(c_ushort.from_param(511)), "<cparam 'H' (511)>")
+        self.assertRegexpMatches(repr(c_int.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
+        self.assertRegexpMatches(repr(c_uint.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
+        self.assertRegexpMatches(repr(c_long.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
+        self.assertRegexpMatches(repr(c_ulong.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
+        self.assertRegexpMatches(repr(c_longlong.from_param(20000)), r"^<cparam '[liq]' \(20000\)>$")
+        self.assertRegexpMatches(repr(c_ulonglong.from_param(20000)), r"^<cparam '[LIQ]' \(20000\)>$")
+        self.assertEqual(repr(c_float.from_param(1.5)), "<cparam 'f' (1.5)>")
+        self.assertEqual(repr(c_double.from_param(1.5)), "<cparam 'd' (1.5)>")
+        self.assertEqual(repr(c_double.from_param(1e300)), "<cparam 'd' (1e+300)>")
+        self.assertRegexpMatches(repr(c_longdouble.from_param(1.5)), r"^<cparam ('d' \(1.5\)|'g' at 0x[A-Fa-f0-9]+)>$")
+        self.assertRegexpMatches(repr(c_char_p.from_param(b'hihi')), "^<cparam 'z' \(0x[A-Fa-f0-9]+\)>$")
+        self.assertRegexpMatches(repr(c_wchar_p.from_param('hihi')), "^<cparam 'Z' \(0x[A-Fa-f0-9]+\)>$")
+        self.assertRegexpMatches(repr(c_void_p.from_param(0x12)), r"^<cparam 'P' \(0x0*12\)>$")
+
 ################################################################

 if __name__ == '__main__':
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -460,50 +460,53 @@ PyCArg_dealloc(PyCArgObject *self)
 static PyObject *
 PyCArg_repr(PyCArgObject *self)
 {
-    char buffer[256];
     switch(self->tag) {
     case 'b':
     case 'B':
-        sprintf(buffer, "<cparam '%c' (%d)>",
+        return PyString_FromFormat("<cparam '%c' (%d)>",
             self->tag, self->value.b);
-        break;
     case 'h':
     case 'H':
-        sprintf(buffer, "<cparam '%c' (%d)>",
+        return PyString_FromFormat("<cparam '%c' (%d)>",
             self->tag, self->value.h);
-        break;
     case 'i':
     case 'I':
-        sprintf(buffer, "<cparam '%c' (%d)>",
+        return PyString_FromFormat("<cparam '%c' (%d)>",
             self->tag, self->value.i);
-        break;
     case 'l':
     case 'L':
-        sprintf(buffer, "<cparam '%c' (%ld)>",
+        return PyString_FromFormat("<cparam '%c' (%ld)>",
             self->tag, self->value.l);
-        break;

 #ifdef HAVE_LONG_LONG
     case 'q':
     case 'Q':
-        sprintf(buffer,
-            "<cparam '%c' (%" PY_FORMAT_LONG_LONG "d)>",
+        return PyString_FromFormat("<cparam '%c' (%" PY_FORMAT_LONG_LONG "d)>",
             self->tag, self->value.q);
-        break;
 #endif
     case 'd':
-        sprintf(buffer, "<cparam '%c' (%f)>",
-            self->tag, self->value.d);
-        break;
-    case 'f':
-        sprintf(buffer, "<cparam '%c' (%f)>",
-            self->tag, self->value.f);
-        break;
+    case 'f': {
+        PyObject *f = PyFloat_FromDouble((self->tag == 'f') ? self->value.f : self->value.d);
+        if (f == NULL) {
+            return NULL;
+        }
+        PyObject *r = PyObject_Repr(f);
+        Py_DECREF(f);
+        if (r == NULL) {
+            return NULL;
+        }
+        char *value = PyString_AsString(r);
+        if (value == NULL) {
+            return NULL;
+        }
+        PyObject *result = PyString_FromFormat("<cparam '%c' (%s)>", self->tag, value);
+        Py_DECREF(r);
+        return result;
+    }

     case 'c':
-        sprintf(buffer, "<cparam '%c' (%c)>",
+        return PyString_FromFormat("<cparam '%c' (%c)>",
             self->tag, self->value.c);
-        break;

 /* Hm, are these 'z' and 'Z' codes useful at all?
    Shouldn't they be replaced by the functionality of c_string
@@ -512,16 +515,13 @@ PyCArg_repr(PyCArgObject *self)
     case 'z':
     case 'Z':
     case 'P':
-        sprintf(buffer, "<cparam '%c' (%p)>",
+        return PyString_FromFormat("<cparam '%c' (%p)>",
             self->tag, self->value.p);
-        break;

     default:
-        sprintf(buffer, "<cparam '%c' at %p>",
+        return PyString_FromFormat("<cparam '%c' at %p>",
             self->tag, self);
-        break;
     }
-    return PyString_FromString(buffer);
 }

 static PyMemberDef PyCArgType_members[] = {


code:
SIGINT is ignored in the Guix build environment.

--- a/Lib/test/test_regrtest.py
+++ b/Lib/test/test_regrtest.py
@@ -399,6 +399,8 @@
         output = self.run_tests('--fromfile', filename)
         self.check_executed_tests(output, tests)

+    @unittest.skipIf(True,
+        "KeyboardInterrupts do not work in the build environment")
     def test_interrupted(self):
         code = TEST_INTERRUPTED
         test = self.create_test('sigint', code=code)
@@ -416,6 +418,8 @@
                  % (self.TESTNAME_REGEX, len(tests)))
         self.check_line(output, regex)

+    @unittest.skipIf(True,
+        "KeyboardInterrupts do not work in the build environment")
     def test_slow_interrupted(self):
         # Issue #25373: test --slowest with an interrupted test
         code = TEST_INTERRUPTED


code:
Make sure the build system honors C_INCLUDE_PATH and LIBRARY_PATH when
looking for headers and libraries.

--- Python-2.7.10/setup.py	2015-10-07 18:33:18.125153186 +0200
+++ Python-2.7.10/setup.py	2015-10-07 18:33:47.497347552 +0200
@@ -526,6 +526,14 @@ class PyBuildExt(build_ext):
             inc_dirs += ['/system/include', '/atheos/autolnk/include']
             inc_dirs += os.getenv('C_INCLUDE_PATH', '').split(os.pathsep)

+        # Always honor these variables.
+        if not cross_compiling:
+            lib_dirs += os.getenv('LIBRARY_PATH', '').split(os.pathsep)
+            inc_dirs += os.getenv('C_INCLUDE_PATH', '').split(os.pathsep)
+        else:
+            lib_dirs = os.getenv('CROSS_LIBRARY_PATH', '').split(os.pathsep)
+            inc_dirs = os.getenv('CROSS_CPATH', '').split(os.pathsep)
+
         # OSF/1 and Unixware have some stuff in /usr/ccs/lib (like -ldb)
         if host_platform in ['osf1', 'unixware7', 'openunix8']:
             lib_dirs += ['/usr/ccs/lib']


code:
Add all /gnu/store/ prefixes found in PYTHONPATH to the prefixes where
site-packages (and .pth files) are searched.

*** Python-2.7.11/Lib/site.py.orig	2016-10-17 23:27:23.746149690 +0200
--- Python-2.7.11/Lib/site.py	2016-10-17 23:44:51.930871644 +0200
***************
*** 65,70 ****
--- 65,82 ----

  # Prefixes for site-packages; add additional prefixes like /usr/local here
  PREFIXES = [sys.prefix, sys.exec_prefix]
+ # Guix: Add all /gnu/store-paths in PYTHONPATH--these are all
+ # "prefixes".  This is required to search .pth files in all python
+ # packages contained in /gnu/store which is required to make
+ # .pth-defined namespace packages work.
+ # This is necessary if the packages are not merged into a single
+ # `site-packages` directory (like when using `guix environment`) but
+ # listed in PYTHONPATH (like when running `guix build`).
+ for p in sys.path:
+     if p.startswith('/gnu/store/'):
+         PREFIXES.append(p[:p.find('/', 44)]) # find first pathsep after hash
+ del p
+
  # Enable per user site-packages directory
  # set it to False to disable the feature or True to force the feature
  ENABLE_USER_SITE = None


code:
Honor the 'SOURCE_DATE_EPOCH' environment variable to allow for
determinitic builds.

--- a/Lib/py_compile.py
+++ b/Lib/py_compile.py
@@ -105,7 +105,10 @@ def compile(file, cfile=None, dfile=None, doraise=False):
     """
     with open(file, 'U') as f:
         try:
-            timestamp = long(os.fstat(f.fileno()).st_mtime)
+            if 'SOURCE_DATE_EPOCH' in os.environ:
+                timestamp = long(os.environ['SOURCE_DATE_EPOCH'])
+            else:
+                timestamp = long(os.fstat(f.fileno()).st_mtime)
         except AttributeError:
             timestamp = long(os.stat(file).st_mtime)
         codestring = f.read()
diff --git a/Python/import.c b/Python/import.c
index e47ce63..7eecf9c 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -945,6 +945,11 @@ write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat, t
     /* Now write the true mtime (as a 32-bit field) */
     fseek(fp, 4L, 0);
     assert(mtime <= 0xFFFFFFFF);
+    if (Py_GETENV("SOURCE_DATE_EPOCH") != NULL) {
+	const char *epoch = Py_GETENV("SOURCE_DATE_EPOCH");
+	mtime = atoi(epoch);
+    }
+
     PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
     fflush(fp);
     fclose(fp);


code:
Ensure memory accesses in the sha3 module are aligned on ARM as it causes
problems when running 32-bit code on a 64-bit kernel.

Patch taken from upstream bug report:
https://bugs.python.org/issue36515

--- a/Modules/_sha3/sha3module.c
+++ b/Modules/_sha3/sha3module.c
@@ -64,6 +64,12 @@
 #define PLATFORM_BYTE_ORDER IS_BIG_ENDIAN
 #endif

+/* Bus error on 32-bit ARM due to un-aligned memory accesses; 64-bit ARM
+ * doesn't complain but un-aligned memory accesses are sub-optimal */
+#if defined(__arm__) || defined(__aarch64__)
+#define NO_MISALIGNED_ACCESSES
+#endif
+
 /* mangle names */
 #define KeccakF1600_FastLoop_Absorb _PySHA3_KeccakF1600_FastLoop_Absorb
 #define Keccak_HashFinal _PySHA3_Keccak_HashFinal


code:
See the discussion about the issues fixed here at:
http://bugs.python.org/issue20868 .

diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/ctypes/test/test_callbacks.py
--- a/Lib/ctypes/test/test_callbacks.py
+++ b/Lib/ctypes/test/test_callbacks.py
@@ -3,6 +3,7 @@ import unittest
 from ctypes import *
 from ctypes.test import need_symbol
 import _ctypes_test
+import platform

 class Callbacks(unittest.TestCase):
     functype = CFUNCTYPE
@@ -176,6 +177,8 @@ class SampleCallbacksTestCase(unittest.TestCase):

         self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)

+    @unittest.skipIf(platform.machine() in ['mips64'],
+                     "This test fails on this platform")
     def test_issue_8959_a(self):
         from ctypes.util import find_library
         libc_path = find_library("c")
diff --git a/Lib/ctypes/test/test_libc.py b/Lib/ctypes/test/test_libc.py
--- a/Lib/ctypes/test/test_libc.py
+++ b/Lib/ctypes/test/test_libc.py
@@ -2,6 +2,7 @@ import unittest

 from ctypes import *
 import _ctypes_test
+import platform

 lib = CDLL(_ctypes_test.__file__)

@@ -17,6 +18,8 @@ class LibTest(unittest.TestCase):
         import math
         self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0))

+    @unittest.skipIf(platform.machine() in ['mips64'],
+                     "This test fails on this platform")
     def test_qsort(self):
         comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char))
         lib.my_qsort.argtypes = c_void_p, c_size_t, c_size_t, comparefunc
diff --git a/Lib/distutils/tests/test_archive_util.py b/Lib/distutils/tests/test_archive_util.py
--- a/Lib/distutils/tests/test_archive_util.py
+++ b/Lib/distutils/tests/test_archive_util.py
@@ -333,6 +333,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
         self.assertEqual(os.path.basename(res), 'archive.tar.xz')
         self.assertEqual(self._tarinfo(res), self._created_files)

+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -362,6 +363,7 @@ class ArchiveUtilTestCase(support.TempdirManager,

     @unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_tarfile_root_owner(self):
         tmpdir =  self._create_files()
         base_name = os.path.join(self.mkdtemp(), 'archive')
diff --git a/Lib/distutils/tests/test_sdist.py b/Lib/distutils/tests/test_sdist.py
--- a/Lib/distutils/tests/test_sdist.py
+++ b/Lib/distutils/tests/test_sdist.py
@@ -443,6 +443,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
                      "The tar command is not found")
     @unittest.skipIf(find_executable('gzip') is None,
                      "The gzip command is not found")
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_distribution_owner_group(self):
         # now building a sdist
         dist, cmd = self.get_cmd()
diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py
--- a/Lib/test/_test_multiprocessing.py
+++ b/Lib/test/_test_multiprocessing.py
@@ -1473,6 +1473,7 @@ class _TestCondition(BaseTestCase):
         if pid is not None:
             os.kill(pid, signal.SIGINT)

+    @unittest.skipIf(True, "This fails for unknown reasons on Guix")
     def test_wait_result(self):
         if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
             pid = os.getpid()
diff --git a/Lib/test/test_asyncio/test_base_events.py b/Lib/test/test_asyncio/test_base_events.py
--- a/Lib/test/test_asyncio/test_base_events.py
+++ b/Lib/test/test_asyncio/test_base_events.py
@@ -1323,6 +1323,8 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
         self._test_create_connection_ip_addr(m_socket, False)

     @patch_socket
+    @unittest.skipUnless(support.is_resource_enabled('network'),
+                         'network is not enabled')
     def test_create_connection_service_name(self, m_socket):
         m_socket.getaddrinfo = socket.getaddrinfo
         sock = m_socket.socket.return_value
diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py
--- a/Lib/test/test_generators.py
+++ b/Lib/test/test_generators.py
@@ -34,6 +34,7 @@ class SignalAndYieldFromTest(unittest.TestCase):
         else:
             return "FAILED"

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment')
     def test_raise_and_yield_from(self):
         gen = self.generator1()
         gen.send(None)
diff --git a/Lib/test/test_normalization.py b/Lib/test/test_normalization.py
--- a/Lib/test/test_normalization.py
+++ b/Lib/test/test_normalization.py
@@ -2,6 +2,7 @@ from test.support import open_urlresource
 import unittest

 from http.client import HTTPException
+from urllib.error import URLError
 import sys
 from unicodedata import normalize, unidata_version

@@ -43,6 +44,8 @@ class NormalizationTest(unittest.TestCase):
         except PermissionError:
             self.skipTest(f"Permission error when downloading {TESTDATAURL} "
                           f"into the test data directory")
+        except URLError:
+            self.skipTest("DNS lookups are not enabled.")
         except (OSError, HTTPException):
             self.fail(f"Could not retrieve {TESTDATAURL}")

diff --git a/Lib/test/test_pathlib.py b/Lib/test/test_pathlib.py
--- a/Lib/test/test_pathlib.py
+++ b/Lib/test/test_pathlib.py
@@ -2134,8 +2134,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
         self.assertEqual(given, expect)
         self.assertEqual(set(p.rglob("FILEd*")), set())

-    @unittest.skipUnless(hasattr(pwd, 'getpwall'),
-                         'pwd module does not expose getpwall()')
+    @unittest.skipIf(True, "Guix builder home is '/' which causes trouble for these tests")
     def test_expanduser(self):
         P = self.cls
         support.import_module('pwd')
diff --git a/Lib/test/test_pdb.py b/Lib/test/test_pdb.py
--- a/Lib/test/test_pdb.py
+++ b/Lib/test/test_pdb.py
@@ -1150,11 +1150,11 @@ def test_pdb_issue_20766():
     > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
     -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
     (Pdb) continue
-    pdb 1: <built-in function default_int_handler>
+    pdb 1: Handlers.SIG_IGN
     > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
     -> sess.set_trace(sys._getframe())
     (Pdb) continue
-    pdb 2: <built-in function default_int_handler>
+    pdb 2: Handlers.SIG_IGN
     """

diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py
--- a/Lib/test/test_regrtest.py
+++ b/Lib/test/test_regrtest.py
@@ -762,6 +762,7 @@ class ArgsTestCase(BaseTestCase):
         output = self.run_tests('--fromfile', filename)
         self.check_executed_tests(output, tests)

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment.')
     def test_interrupted(self):
         code = TEST_INTERRUPTED
         test = self.create_test('sigint', code=code)
@@ -779,6 +780,7 @@ class ArgsTestCase(BaseTestCase):
                  % (self.TESTNAME_REGEX, len(tests)))
         self.check_line(output, regex)

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment.')
     def test_slowest_interrupted(self):
         # Issue #25373: test --slowest with an interrupted test
         code = TEST_INTERRUPTED
diff --git a/Lib/test/test_resource.py b/Lib/test/test_resource.py
--- a/Lib/test/test_resource.py
+++ b/Lib/test/test_resource.py
@@ -145,6 +145,7 @@ class ResourceTest(unittest.TestCase):

     @unittest.skipUnless(hasattr(resource, 'prlimit'), 'no prlimit')
     @support.requires_linux_version(2, 6, 36)
+    @unittest.skipIf(True, "Bug: the PermissionError is not raised")
     def test_prlimit(self):
         self.assertRaises(TypeError, resource.prlimit)
         self.assertRaises(ProcessLookupError, resource.prlimit,
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -1143,6 +1143,7 @@ class TestShutil(unittest.TestCase):
         self.assertRaises(ValueError, make_archive, base_name, 'xxx')

     @support.requires_zlib
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -1171,6 +1172,7 @@ class TestShutil(unittest.TestCase):

     @support.requires_zlib
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
     def test_tarfile_root_owner(self):
         root_dir, base_dir = self._create_files()
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -875,6 +875,8 @@ class GeneralModuleTests(unittest.TestCase):
         if not fqhn in all_host_names:
             self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))

+    @unittest.skipUnless(support.is_resource_enabled('network'),
+                         'network is not enabled')
     def test_host_resolution(self):
         for addr in [support.HOSTv4, '10.0.0.1', '255.255.255.255']:
             self.assertEqual(socket.gethostbyname(addr), addr)
@@ -1004,6 +1006,8 @@ class GeneralModuleTests(unittest.TestCase):
             self.assertWarns(DeprecationWarning, socket.ntohs, k)
             self.assertWarns(DeprecationWarning, socket.htons, k)

+    @unittest.skipUnless(os.path.exists("/etc/services"),
+                         "getservbyname uses /etc/services, which is not in the chroot")
     def testGetServBy(self):
         eq = self.assertEqual
         # Find one service that exists, then check all the related interfaces.
@@ -1358,6 +1362,8 @@ class GeneralModuleTests(unittest.TestCase):
             raise
         self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None)

+    @unittest.skipUnless(os.path.exists("/etc/gai.conf"),
+                         "getaddrinfo() will fail")
     def testGetaddrinfo(self):
         try:
             socket.getaddrinfo('localhost', 80)
@@ -1440,6 +1446,8 @@ class GeneralModuleTests(unittest.TestCase):
         # only IP addresses are allowed
         self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)

+    @unittest.skipUnless(os.path.exists("/etc/gai.conf"),
+                         "getaddrinfo() will fail")
     @unittest.skipUnless(support.is_resource_enabled('network'),
                          'network is not enabled')
     def test_idna(self):
diff --git a/Lib/test/test_spwd.py b/Lib/test/test_spwd.py
--- a/Lib/test/test_spwd.py
+++ b/Lib/test/test_spwd.py
@@ -5,8 +5,7 @@ from test import support
 spwd = support.import_module('spwd')

-@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
-                     'root privileges required')
+@unittest.skipUnless(os.path.exists("/etc/shadow"), 'spwd tests require /etc/shadow')
 class TestSpwdRoot(unittest.TestCase):

     def test_getspall(self):
@@ -56,8 +55,7 @@ class TestSpwdRoot(unittest.TestCase):
             self.assertRaises(TypeError, spwd.getspnam, bytes_name)

-@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() != 0,
-                     'non-root user required')
+@unittest.skipUnless(os.path.exists("/etc/shadow"), 'spwd tests require /etc/shadow')
 class TestSpwdNonRoot(unittest.TestCase):

     def test_getspnam_exception(self):
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -2509,9 +2509,12 @@ def root_is_uid_gid_0():
         import pwd, grp
     except ImportError:
         return False
-    if pwd.getpwuid(0)[0] != 'root':
-        return False
-    if grp.getgrgid(0)[0] != 'root':
+    try:
+        if pwd.getpwuid(0)[0] != 'root':
+            return False
+        if grp.getgrgid(0)[0] != 'root':
+            return False
+    except KeyError:
         return False
     return True

diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -1249,6 +1249,7 @@ class MiscTestCase(unittest.TestCase):

 class InterruptMainTests(unittest.TestCase):
+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build container.')
     def test_interrupt_main_subthread(self):
         # Calling start_new_thread with a function that executes interrupt_main
         # should raise KeyboardInterrupt upon completion.
@@ -1260,6 +1261,8 @@ class InterruptMainTests(unittest.TestCase):
             t.join()
         t.join()

+
+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build container.')
     def test_interrupt_main_mainthread(self):
         # Make sure that if interrupt_main is called in main thread that
         # KeyboardInterrupt is raised instantly.
diff --git a/Tools/scripts/run_tests.py b/Tools/scripts/run_tests.py
--- a/Tools/scripts/run_tests.py
+++ b/Tools/scripts/run_tests.py
@@ -39,7 +39,7 @@ def main(regrtest_args):
     if not any(is_multiprocess_flag(arg) for arg in regrtest_args):
         args.extend(['-j', '0'])  # Use all CPU cores
     if not any(is_resource_use_flag(arg) for arg in regrtest_args):
-        args.extend(['-u', 'all,-largefile,-audio,-gui'])
+        args.extend(['-u', 'all,-largefile,-audio,-gui,-network'])
     args.extend(regrtest_args)
     print(' '.join(args))
     if sys.platform == 'win32':


code:
Make sure the build system honors C_INCLUDE_PATH and LIBRARY_PATH when
looking for headers and libraries.

--- a/setup.py	2015-10-07 23:32:58.891329173 +0200
+++ b/setup.py	2015-10-07 23:46:29.653349924 +0200
@@ -676,15 +676,15 @@
         # if a file is found in one of those directories, it can
         # be assumed that no additional -I,-L directives are needed.
         if not CROSS_COMPILING:
-            self.lib_dirs = self.compiler.library_dirs + system_lib_dirs
-            self.inc_dirs = self.compiler.include_dirs + system_include_dirs
+            self.lib_dirs = os.getenv('LIBRARY_PATH', '').split(os.pathsep)
+            self.inc_dirs = os.getenv('C_INCLUDE_PATH', '').split(os.pathsep)
         else:
             # Add the sysroot paths. 'sysroot' is a compiler option used to
             # set the logical path of the standard system headers and
             # libraries.
-            self.lib_dirs = (self.compiler.library_dirs +
+            self.lib_dirs = (os.getenv('CROSS_LIBRARY_PATH', '').split(os.pathsep) +
                              sysroot_paths(('LDFLAGS', 'CC'), system_lib_dirs))
-            self.inc_dirs = (self.compiler.include_dirs +
+            self.inc_dirs = (os.getenv('CROSS_C_INCLUDE_PATH', '').split(os.pathsep) +
                              sysroot_paths(('CPPFLAGS', 'CFLAGS', 'CC'),
                                            system_include_dirs))


code:
Fix CVE-2021-3177 for Python 3.8:

https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-3177

Patch copied from upstream source repository:

https://github.com/python/cpython/commit/ece5dfd403dac211f8d3c72701fe7ba7b7aa5b5f

From ece5dfd403dac211f8d3c72701fe7ba7b7aa5b5f Mon Sep 17 00:00:00 2001
From: "Miss Islington (bot)"
 <31488909+miss-islington@users.noreply.github.com>
Date: Mon, 18 Jan 2021 13:28:52 -0800
Subject: [PATCH] closes bpo-42938: Replace snprintf with Python unicode
 formatting in ctypes param reprs. (GH-24248)

(cherry picked from commit 916610ef90a0d0761f08747f7b0905541f0977c7)

Co-authored-by: Benjamin Peterson <benjamin@python.org>

Co-authored-by: Benjamin Peterson <benjamin@python.org>
---
 Lib/ctypes/test/test_parameters.py            | 43 ++++++++++++++++
 .../2021-01-18-09-27-31.bpo-42938.4Zn4Mp.rst  |  2 +
 Modules/_ctypes/callproc.c                    | 51 +++++++------------
 3 files changed, 64 insertions(+), 32 deletions(-)
 create mode 100644 Misc/NEWS.d/next/Security/2021-01-18-09-27-31.bpo-42938.4Zn4Mp.rst

diff --git a/Lib/ctypes/test/test_parameters.py b/Lib/ctypes/test/test_parameters.py
index e4c25fd880cef..531894fdec838 100644
--- a/Lib/ctypes/test/test_parameters.py
+++ b/Lib/ctypes/test/test_parameters.py
@@ -201,6 +201,49 @@ def __dict__(self):
         with self.assertRaises(ZeroDivisionError):
             WorseStruct().__setstate__({}, b'foo')

+    def test_parameter_repr(self):
+        from ctypes import (
+            c_bool,
+            c_char,
+            c_wchar,
+            c_byte,
+            c_ubyte,
+            c_short,
+            c_ushort,
+            c_int,
+            c_uint,
+            c_long,
+            c_ulong,
+            c_longlong,
+            c_ulonglong,
+            c_float,
+            c_double,
+            c_longdouble,
+            c_char_p,
+            c_wchar_p,
+            c_void_p,
+        )
+        self.assertRegex(repr(c_bool.from_param(True)), r"^<cparam '\?' at 0x[A-Fa-f0-9]+>$")
+        self.assertEqual(repr(c_char.from_param(97)), "<cparam 'c' ('a')>")
+        self.assertRegex(repr(c_wchar.from_param('a')), r"^<cparam 'u' at 0x[A-Fa-f0-9]+>$")
+        self.assertEqual(repr(c_byte.from_param(98)), "<cparam 'b' (98)>")
+        self.assertEqual(repr(c_ubyte.from_param(98)), "<cparam 'B' (98)>")
+        self.assertEqual(repr(c_short.from_param(511)), "<cparam 'h' (511)>")
+        self.assertEqual(repr(c_ushort.from_param(511)), "<cparam 'H' (511)>")
+        self.assertRegex(repr(c_int.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
+        self.assertRegex(repr(c_uint.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
+        self.assertRegex(repr(c_long.from_param(20000)), r"^<cparam '[li]' \(20000\)>$")
+        self.assertRegex(repr(c_ulong.from_param(20000)), r"^<cparam '[LI]' \(20000\)>$")
+        self.assertRegex(repr(c_longlong.from_param(20000)), r"^<cparam '[liq]' \(20000\)>$")
+        self.assertRegex(repr(c_ulonglong.from_param(20000)), r"^<cparam '[LIQ]' \(20000\)>$")
+        self.assertEqual(repr(c_float.from_param(1.5)), "<cparam 'f' (1.5)>")
+        self.assertEqual(repr(c_double.from_param(1.5)), "<cparam 'd' (1.5)>")
+        self.assertEqual(repr(c_double.from_param(1e300)), "<cparam 'd' (1e+300)>")
+        self.assertRegex(repr(c_longdouble.from_param(1.5)), r"^<cparam ('d' \(1.5\)|'g' at 0x[A-Fa-f0-9]+)>$")
+        self.assertRegex(repr(c_char_p.from_param(b'hihi')), "^<cparam 'z' \(0x[A-Fa-f0-9]+\)>$")
+        self.assertRegex(repr(c_wchar_p.from_param('hihi')), "^<cparam 'Z' \(0x[A-Fa-f0-9]+\)>$")
+        self.assertRegex(repr(c_void_p.from_param(0x12)), r"^<cparam 'P' \(0x0*12\)>$")
+
 ################################################################

 if __name__ == '__main__':
#diff --git a/Misc/NEWS.d/next/Security/2021-01-18-09-27-31.bpo-42938.4Zn4Mp.rst b/Misc/NEWS.d/next/Security/2021-01-18-09-27-31.bpo-42938.4Zn4Mp.rst
#new file mode 100644
#index 0000000000000..7df65a156feab
#--- /dev/null
#+++ b/Misc/NEWS.d/next/Security/2021-01-18-09-27-31.bpo-42938.4Zn4Mp.rst
#@@ -0,0 +1,2 @@
#+Avoid static buffers when computing the repr of :class:`ctypes.c_double` and
#+:class:`ctypes.c_longdouble` values.
diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c
index a9b8675cd951b..de75918d49f37 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -484,58 +484,47 @@ is_literal_char(unsigned char c)
 static PyObject *
 PyCArg_repr(PyCArgObject *self)
 {
-    char buffer[256];
     switch(self->tag) {
     case 'b':
     case 'B':
-        sprintf(buffer, "<cparam '%c' (%d)>",
+        return PyUnicode_FromFormat("<cparam '%c' (%d)>",
             self->tag, self->value.b);
-        break;
     case 'h':
     case 'H':
-        sprintf(buffer, "<cparam '%c' (%d)>",
+        return PyUnicode_FromFormat("<cparam '%c' (%d)>",
             self->tag, self->value.h);
-        break;
     case 'i':
     case 'I':
-        sprintf(buffer, "<cparam '%c' (%d)>",
+        return PyUnicode_FromFormat("<cparam '%c' (%d)>",
             self->tag, self->value.i);
-        break;
     case 'l':
     case 'L':
-        sprintf(buffer, "<cparam '%c' (%ld)>",
+        return PyUnicode_FromFormat("<cparam '%c' (%ld)>",
             self->tag, self->value.l);
-        break;

     case 'q':
     case 'Q':
-        sprintf(buffer,
-#ifdef MS_WIN32
-            "<cparam '%c' (%I64d)>",
-#else
-            "<cparam '%c' (%lld)>",
-#endif
+        return PyUnicode_FromFormat("<cparam '%c' (%lld)>",
             self->tag, self->value.q);
-        break;
     case 'd':
-        sprintf(buffer, "<cparam '%c' (%f)>",
-            self->tag, self->value.d);
-        break;
-    case 'f':
-        sprintf(buffer, "<cparam '%c' (%f)>",
-            self->tag, self->value.f);
-        break;
-
+    case 'f': {
+        PyObject *f = PyFloat_FromDouble((self->tag == 'f') ? self->value.f : self->value.d);
+        if (f == NULL) {
+            return NULL;
+        }
+        PyObject *result = PyUnicode_FromFormat("<cparam '%c' (%R)>", self->tag, f);
+        Py_DECREF(f);
+        return result;
+    }
     case 'c':
         if (is_literal_char((unsigned char)self->value.c)) {
-            sprintf(buffer, "<cparam '%c' ('%c')>",
+            return PyUnicode_FromFormat("<cparam '%c' ('%c')>",
                 self->tag, self->value.c);
         }
         else {
-            sprintf(buffer, "<cparam '%c' ('\\x%02x')>",
+            return PyUnicode_FromFormat("<cparam '%c' ('\\x%02x')>",
                 self->tag, (unsigned char)self->value.c);
         }
-        break;

 /* Hm, are these 'z' and 'Z' codes useful at all?
    Shouldn't they be replaced by the functionality of c_string
@@ -544,22 +533,20 @@ PyCArg_repr(PyCArgObject *self)
     case 'z':
     case 'Z':
     case 'P':
-        sprintf(buffer, "<cparam '%c' (%p)>",
+        return PyUnicode_FromFormat("<cparam '%c' (%p)>",
             self->tag, self->value.p);
         break;

     default:
         if (is_literal_char((unsigned char)self->tag)) {
-            sprintf(buffer, "<cparam '%c' at %p>",
+            return PyUnicode_FromFormat("<cparam '%c' at %p>",
                 (unsigned char)self->tag, (void *)self);
         }
         else {
-            sprintf(buffer, "<cparam 0x%02x at %p>",
+            return PyUnicode_FromFormat("<cparam 0x%02x at %p>",
                 (unsigned char)self->tag, (void *)self);
         }
-        break;
     }
-    return PyUnicode_FromString(buffer);
 }

 static PyMemberDef PyCArgType_members[] = {


code:
diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py
index 1474624..887f8ee 100644
--- a/Lib/test/_test_multiprocessing.py
+++ b/Lib/test/_test_multiprocessing.py
@@ -3801,6 +3801,7 @@ class _TestSharedMemory(BaseTestCase):
         sms.close()

     @unittest.skipIf(os.name != "posix", "not feasible in non-posix platforms")
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_shared_memory_SharedMemoryServer_ignores_sigint(self):
         # bpo-36368: protect SharedMemoryManager server process from
         # KeyboardInterrupt signals.
diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py
index d41e94b..a1c15e7 100644
--- a/Lib/test/test_signal.py
+++ b/Lib/test/test_signal.py
@@ -78,6 +78,7 @@ class PosixTests(unittest.TestCase):
         self.assertLess(len(s), signal.NSIG)

     @unittest.skipUnless(sys.executable, "sys.executable required.")
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_keyboard_interrupt_exit_code(self):
         """KeyboardInterrupt triggers exit via SIGINT."""
         process = subprocess.run(
@@ -128,6 +129,7 @@ class WindowsSignalTests(unittest.TestCase):
             signal.signal(7, handler)

     @unittest.skipUnless(sys.executable, "sys.executable required.")
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_keyboard_interrupt_exit_code(self):
         """KeyboardInterrupt triggers an exit using STATUS_CONTROL_C_EXIT."""
         # We don't test via os.kill(os.getpid(), signal.CTRL_C_EVENT) here
@@ -1245,6 +1247,7 @@ class StressTest(unittest.TestCase):

 class RaiseSignalTest(unittest.TestCase):

+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_sigint(self):
         with self.assertRaises(KeyboardInterrupt):
             signal.raise_signal(signal.SIGINT)
--
2.23.0


code:
See the discussion about the issues fixed here at:
http://bugs.python.org/issue20868 .

diff --git a/Lib/ctypes/test/test_callbacks.py b/Lib/ctypes/test/test_callbacks.py
--- a/Lib/ctypes/test/test_callbacks.py
+++ b/Lib/ctypes/test/test_callbacks.py
@@ -3,6 +3,7 @@ import unittest
 from ctypes import *
 from ctypes.test import need_symbol
 import _ctypes_test
+import platform

 class Callbacks(unittest.TestCase):
     functype = CFUNCTYPE
@@ -176,6 +177,8 @@ class SampleCallbacksTestCase(unittest.TestCase):

         self.assertLess(diff, 0.01, "%s not less than 0.01" % diff)

+    @unittest.skipIf(platform.machine() in ['mips64'],
+                     "This test fails on this platform")
     def test_issue_8959_a(self):
         from ctypes.util import find_library
         libc_path = find_library("c")
diff --git a/Lib/ctypes/test/test_libc.py b/Lib/ctypes/test/test_libc.py
--- a/Lib/ctypes/test/test_libc.py
+++ b/Lib/ctypes/test/test_libc.py
@@ -2,6 +2,7 @@ import unittest

 from ctypes import *
 import _ctypes_test
+import platform

 lib = CDLL(_ctypes_test.__file__)

@@ -17,6 +18,8 @@ class LibTest(unittest.TestCase):
         import math
         self.assertEqual(lib.my_sqrt(2.0), math.sqrt(2.0))

+    @unittest.skipIf(platform.machine() in ['mips64'],
+                     "This test fails on this platform")
     def test_qsort(self):
         comparefunc = CFUNCTYPE(c_int, POINTER(c_char), POINTER(c_char))
         lib.my_qsort.argtypes = c_void_p, c_size_t, c_size_t, comparefunc
diff --git a/Lib/distutils/tests/test_archive_util.py b/Lib/distutils/tests/test_archive_util.py
--- a/Lib/distutils/tests/test_archive_util.py
+++ b/Lib/distutils/tests/test_archive_util.py
@@ -333,6 +333,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
         self.assertEqual(os.path.basename(res), 'archive.tar.xz')
         self.assertEqual(self._tarinfo(res), self._created_files)

+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -362,6 +363,7 @@ class ArchiveUtilTestCase(support.TempdirManager,

     @unittest.skipUnless(ZLIB_SUPPORT, "Requires zlib")
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_tarfile_root_owner(self):
         tmpdir =  self._create_files()
         base_name = os.path.join(self.mkdtemp(), 'archive')
diff --git a/Lib/distutils/tests/test_sdist.py b/Lib/distutils/tests/test_sdist.py
--- a/Lib/distutils/tests/test_sdist.py
+++ b/Lib/distutils/tests/test_sdist.py
@@ -443,6 +443,7 @@ class SDistTestCase(BasePyPIRCCommandTestCase):
                      "The tar command is not found")
     @unittest.skipIf(find_executable('gzip') is None,
                      "The gzip command is not found")
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_distribution_owner_group(self):
         # now building a sdist
         dist, cmd = self.get_cmd()
diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py
--- a/Lib/test/_test_multiprocessing.py
+++ b/Lib/test/_test_multiprocessing.py
@@ -1473,6 +1473,7 @@ class _TestCondition(BaseTestCase):
         if pid is not None:
             os.kill(pid, signal.SIGINT)

+    @unittest.skipIf(True, "This fails for unknown reasons on Guix")
     def test_wait_result(self):
         if isinstance(self, ProcessesMixin) and sys.platform != 'win32':
             pid = os.getpid()
diff --git a/Lib/test/test_asyncio/test_base_events.py b/Lib/test/test_asyncio/test_base_events.py
--- a/Lib/test/test_asyncio/test_base_events.py
+++ b/Lib/test/test_asyncio/test_base_events.py
@@ -1323,6 +1323,8 @@ class BaseEventLoopWithSelectorTests(test_utils.TestCase):
         self._test_create_connection_ip_addr(m_socket, False)

     @patch_socket
+    @unittest.skipUnless(support.is_resource_enabled('network'),
+                         'network is not enabled')
     def test_create_connection_service_name(self, m_socket):
         m_socket.getaddrinfo = socket.getaddrinfo
         sock = m_socket.socket.return_value
diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py
--- a/Lib/test/test_generators.py
+++ b/Lib/test/test_generators.py
@@ -34,6 +34,7 @@ class SignalAndYieldFromTest(unittest.TestCase):
         else:
             return "FAILED"

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment')
     def test_raise_and_yield_from(self):
         gen = self.generator1()
         gen.send(None)
diff --git a/Lib/test/test_pathlib.py b/Lib/test/test_pathlib.py
--- a/Lib/test/test_pathlib.py
+++ b/Lib/test/test_pathlib.py
@@ -2134,8 +2134,7 @@ class PosixPathTest(_BasePathTest, unittest.TestCase):
         self.assertEqual(given, expect)
         self.assertEqual(set(p.rglob("FILEd*")), set())

-    @unittest.skipUnless(hasattr(pwd, 'getpwall'),
-                         'pwd module does not expose getpwall()')
+    @unittest.skipIf(True, "Guix builder home is '/' which causes trouble for these tests")
     def test_expanduser(self):
         P = self.cls
         support.import_module('pwd')
diff --git a/Lib/test/test_pdb.py b/Lib/test/test_pdb.py
--- a/Lib/test/test_pdb.py
+++ b/Lib/test/test_pdb.py
@@ -1150,11 +1150,11 @@ def test_pdb_issue_20766():
     > <doctest test.test_pdb.test_pdb_issue_20766[0]>(6)test_function()
     -> print('pdb %d: %s' % (i, sess._previous_sigint_handler))
     (Pdb) continue
-    pdb 1: <built-in function default_int_handler>
+    pdb 1: Handlers.SIG_IGN
     > <doctest test.test_pdb.test_pdb_issue_20766[0]>(5)test_function()
     -> sess.set_trace(sys._getframe())
     (Pdb) continue
-    pdb 2: <built-in function default_int_handler>
+    pdb 2: Handlers.SIG_IGN
     """

diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py
--- a/Lib/test/test_regrtest.py
+++ b/Lib/test/test_regrtest.py
@@ -762,6 +762,7 @@ class ArgsTestCase(BaseTestCase):
         output = self.run_tests('--fromfile', filename)
         self.check_executed_tests(output, tests)

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment.')
     def test_interrupted(self):
         code = TEST_INTERRUPTED
         test = self.create_test('sigint', code=code)
@@ -779,6 +780,7 @@ class ArgsTestCase(BaseTestCase):
                  % (self.TESTNAME_REGEX, len(tests)))
         self.check_line(output, regex)

+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build environment.')
     def test_slowest_interrupted(self):
         # Issue #25373: test --slowest with an interrupted test
         code = TEST_INTERRUPTED
diff --git a/Lib/test/test_resource.py b/Lib/test/test_resource.py
--- a/Lib/test/test_resource.py
+++ b/Lib/test/test_resource.py
@@ -145,6 +145,7 @@ class ResourceTest(unittest.TestCase):

     @unittest.skipUnless(hasattr(resource, 'prlimit'), 'no prlimit')
     @support.requires_linux_version(2, 6, 36)
+    @unittest.skipIf(True, "Bug: the PermissionError is not raised")
     def test_prlimit(self):
         self.assertRaises(TypeError, resource.prlimit)
         self.assertRaises(ProcessLookupError, resource.prlimit,
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -1428,6 +1428,7 @@ class TestArchives(BaseTest, unittest.TestCase):
         self.assertRaises(ValueError, make_archive, base_name, 'xxx')

     @support.requires_zlib()
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     def test_make_archive_owner_group(self):
         # testing make_archive with owner and group, with various combinations
         # this works even if there's not gid/uid support
@@ -1456,6 +1457,7 @@ class TestArchives(BaseTest, unittest.TestCase):

     @support.requires_zlib()
+    @unittest.skipIf(True, "getgrgid(0)[0] raises a KeyError on Guix")
     @unittest.skipUnless(UID_GID_SUPPORT, "Requires grp and pwd support")
     def test_tarfile_root_owner(self):
         root_dir, base_dir = self._create_files()
diff --git a/Lib/test/test_unicodedata.py b/Lib/test/test_unicodedata.py
--- a/Lib/test/test_unicodedata.py
+++ b/Lib/test/test_unicodedata.py
@@ -320,6 +320,7 @@ class NormalizationTest(unittest.TestCase):
         data = [int(x, 16) for x in data.split(" ")]
         return "".join([chr(x) for x in data])

+    @unittest.skipIf(True, 'Network is not available in the Guix build environment')
     def test_normalization(self):
         TESTDATAFILE = "NormalizationTest.txt"
         TESTDATAURL = f"http://www.pythontest.net/unicode/{unicodedata.unidata_version}/{TESTDATAFILE}"
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -875,6 +875,8 @@ class GeneralModuleTests(unittest.TestCase):
         if not fqhn in all_host_names:
             self.fail("Error testing host resolution mechanisms. (fqdn: %s, all: %s)" % (fqhn, repr(all_host_names)))

+    @unittest.skipUnless(support.is_resource_enabled('network'),
+                         'network is not enabled')
     def test_host_resolution(self):
         for addr in [support.HOSTv4, '10.0.0.1', '255.255.255.255']:
             self.assertEqual(socket.gethostbyname(addr), addr)
@@ -1004,6 +1006,8 @@ class GeneralModuleTests(unittest.TestCase):
             self.assertWarns(DeprecationWarning, socket.ntohs, k)
             self.assertWarns(DeprecationWarning, socket.htons, k)

+    @unittest.skipUnless(os.path.exists("/etc/services"),
+                         "getservbyname uses /etc/services, which is not in the chroot")
     def testGetServBy(self):
         eq = self.assertEqual
         # Find one service that exists, then check all the related interfaces.
@@ -1358,6 +1362,8 @@ class GeneralModuleTests(unittest.TestCase):
             raise
         self.assertRaises(TypeError, s.ioctl, socket.SIO_LOOPBACK_FAST_PATH, None)

+    @unittest.skipUnless(os.path.exists("/etc/gai.conf"),
+                         "getaddrinfo() will fail")
     def testGetaddrinfo(self):
         try:
             socket.getaddrinfo('localhost', 80)
@@ -1440,6 +1446,8 @@ class GeneralModuleTests(unittest.TestCase):
         # only IP addresses are allowed
         self.assertRaises(OSError, socket.getnameinfo, ('mail.python.org',0), 0)

+    @unittest.skipUnless(os.path.exists("/etc/gai.conf"),
+                         "getaddrinfo() will fail")
     @unittest.skipUnless(support.is_resource_enabled('network'),
                          'network is not enabled')
     def test_idna(self):
diff --git a/Lib/test/test_spwd.py b/Lib/test/test_spwd.py
--- a/Lib/test/test_spwd.py
+++ b/Lib/test/test_spwd.py
@@ -5,8 +5,7 @@ from test import support
 spwd = support.import_module('spwd')

-@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() == 0,
-                     'root privileges required')
+@unittest.skipUnless(os.path.exists("/etc/shadow"), 'spwd tests require /etc/shadow')
 class TestSpwdRoot(unittest.TestCase):

     def test_getspall(self):
@@ -56,8 +55,7 @@ class TestSpwdRoot(unittest.TestCase):
             self.assertRaises(TypeError, spwd.getspnam, bytes_name)

-@unittest.skipUnless(hasattr(os, 'geteuid') and os.geteuid() != 0,
-                     'non-root user required')
+@unittest.skipUnless(os.path.exists("/etc/shadow"), 'spwd tests require /etc/shadow')
 class TestSpwdNonRoot(unittest.TestCase):

     def test_getspnam_exception(self):
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -2509,9 +2509,12 @@ def root_is_uid_gid_0():
         import pwd, grp
     except ImportError:
         return False
-    if pwd.getpwuid(0)[0] != 'root':
-        return False
-    if grp.getgrgid(0)[0] != 'root':
+    try:
+        if pwd.getpwuid(0)[0] != 'root':
+            return False
+        if grp.getgrgid(0)[0] != 'root':
+            return False
+    except KeyError:
         return False
     return True

diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -1249,6 +1249,7 @@ class MiscTestCase(unittest.TestCase):

 class InterruptMainTests(unittest.TestCase):
+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build container.')
     def test_interrupt_main_subthread(self):
         # Calling start_new_thread with a function that executes interrupt_main
         # should raise KeyboardInterrupt upon completion.
@@ -1260,6 +1261,8 @@ class InterruptMainTests(unittest.TestCase):
             t.join()
         t.join()

+
+    @unittest.skipIf(True, 'Keyboard interrupts do not work in the Guix build container.')
     def test_interrupt_main_mainthread(self):
         # Make sure that if interrupt_main is called in main thread that
         # KeyboardInterrupt is raised instantly.
diff --git a/Tools/scripts/run_tests.py b/Tools/scripts/run_tests.py
--- a/Tools/scripts/run_tests.py
+++ b/Tools/scripts/run_tests.py
@@ -39,7 +39,7 @@ def main(regrtest_args):
     if not any(is_multiprocess_flag(arg) for arg in regrtest_args):
         args.extend(['-j', '0'])  # Use all CPU cores
     if not any(is_resource_use_flag(arg) for arg in regrtest_args):
-        args.extend(['-u', 'all,-largefile,-audio,-gui'])
+        args.extend(['-u', 'all,-largefile,-audio,-gui,-network'])
     args.extend(regrtest_args)
     print(' '.join(args))
     if sys.platform == 'win32':
diff --git a/Lib/test/_test_multiprocessing.py b/Lib/test/_test_multiprocessing.py
index 1474624..887f8ee 100644
--- a/Lib/test/_test_multiprocessing.py
+++ b/Lib/test/_test_multiprocessing.py
@@ -3801,6 +3801,7 @@ class _TestSharedMemory(BaseTestCase):
         sms.close()

     @unittest.skipIf(os.name != "posix", "not feasible in non-posix platforms")
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_shared_memory_SharedMemoryServer_ignores_sigint(self):
         # bpo-36368: protect SharedMemoryManager server process from
         # KeyboardInterrupt signals.
diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py
index d41e94b..a1c15e7 100644
--- a/Lib/test/test_signal.py
+++ b/Lib/test/test_signal.py
@@ -78,6 +78,7 @@ class PosixTests(unittest.TestCase):
         self.assertLess(len(s), signal.NSIG)

     @unittest.skipUnless(sys.executable, "sys.executable required.")
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_keyboard_interrupt_exit_code(self):
         """KeyboardInterrupt triggers exit via SIGINT."""
         process = subprocess.run(
@@ -128,6 +129,7 @@ class WindowsSignalTests(unittest.TestCase):
             signal.signal(7, handler)

     @unittest.skipUnless(sys.executable, "sys.executable required.")
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_keyboard_interrupt_exit_code(self):
         """KeyboardInterrupt triggers an exit using STATUS_CONTROL_C_EXIT."""
         # We don't test via os.kill(os.getpid(), signal.CTRL_C_EVENT) here
@@ -1245,6 +1247,7 @@ class StressTest(unittest.TestCase):

 class RaiseSignalTest(unittest.TestCase):

+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_sigint(self):
         with self.assertRaises(KeyboardInterrupt):
             signal.raise_signal(signal.SIGINT)
@@ -1279,6 +1279,7 @@ class PidfdSignalTest(unittest.TestCase):
         hasattr(signal, "pidfd_send_signal"),
         "pidfd support not built in",
     )
+    @unittest.skipUnless(sys.stdin.isatty(), "KeyboardInterrupts require a TTY device")
     def test_pidfd_send_signal(self):
         with self.assertRaises(OSError) as cm:
             signal.pidfd_send_signal(0, signal.SIGINT)
diff --git a/Lib/ctypes/test/test_find.py b/Lib/ctypes/test/test_find.py
index 92ac184..49eec2c 100644
--- a/Lib/ctypes/test/test_find.py
+++ b/Lib/ctypes/test/test_find.py
@@ -116,6 +116,7 @@ class FindLibraryLinux(unittest.TestCase):
         with unittest.mock.patch("ctypes.util._findSoname_ldconfig", lambda *args: None):
             self.assertNotEqual(find_library('c'), None)

+    @unittest.skipIf(True, "This fails for unknown reasons on Guix")
     def test_find_library_with_ld(self):
         with unittest.mock.patch("ctypes.util._findSoname_ldconfig", lambda *args: None), \
              unittest.mock.patch("ctypes.util._findLib_gcc", lambda *args: None):


code:
Fix CVE-2018-14647:
https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2018-14647
https://bugs.python.org/issue34623

Taken from upstream:
https://github.com/python/cpython/commit/f7666e828cc3d5873136473ea36ba2013d624fa1

diff --git Include/pyexpat.h Include/pyexpat.h
index 44259bf6d7..07020b5dc9 100644
--- Include/pyexpat.h
+++ Include/pyexpat.h
@@ -3,7 +3,7 @@

 /* note: you must import expat.h before importing this module! */

-#define PyExpat_CAPI_MAGIC  "pyexpat.expat_CAPI 1.0"
+#define PyExpat_CAPI_MAGIC  "pyexpat.expat_CAPI 1.1"
 #define PyExpat_CAPSULE_NAME "pyexpat.expat_CAPI"

 struct PyExpat_CAPI
@@ -48,6 +48,8 @@ struct PyExpat_CAPI
     enum XML_Status (*SetEncoding)(XML_Parser parser, const XML_Char *encoding);
     int (*DefaultUnknownEncodingHandler)(
         void *encodingHandlerData, const XML_Char *name, XML_Encoding *info);
+    /* might be none for expat < 2.1.0 */
+    int (*SetHashSalt)(XML_Parser parser, unsigned long hash_salt);
     /* always add new stuff to the end! */
 };

diff --git Modules/_elementtree.c Modules/_elementtree.c
index 707ab2912b..53f05f937f 100644
--- Modules/_elementtree.c
+++ Modules/_elementtree.c
@@ -3261,6 +3261,11 @@ _elementtree_XMLParser___init___impl(XMLParserObject *self, PyObject *html,
         PyErr_NoMemory();
         return -1;
     }
+    /* expat < 2.1.0 has no XML_SetHashSalt() */
+    if (EXPAT(SetHashSalt) != NULL) {
+        EXPAT(SetHashSalt)(self->parser,
+                           (unsigned long)_Py_HashSecret.expat.hashsalt);
+    }

     if (target) {
         Py_INCREF(target);
diff --git Modules/pyexpat.c Modules/pyexpat.c
index 47c3e86c20..aa21d93c11 100644
--- Modules/pyexpat.c
+++ Modules/pyexpat.c
@@ -1887,6 +1887,11 @@ MODULE_INITFUNC(void)
     capi.SetStartDoctypeDeclHandler = XML_SetStartDoctypeDeclHandler;
     capi.SetEncoding = XML_SetEncoding;
     capi.DefaultUnknownEncodingHandler = PyUnknownEncodingHandler;
+#if XML_COMBINED_VERSION >= 20100
+    capi.SetHashSalt = XML_SetHashSalt;
+#else
+    capi.SetHashSalt = NULL;
+#endif

     /* export using capsule */
     capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);


code:
Fix CVE-2020-26116:

https://cve.circl.lu/cve/CVE-2020-26116
https://bugs.python.org/issue39603

Taken from upstream (sans test and NEWS update):
https://github.com/python/cpython/commit/668d321476d974c4f51476b33aaca870272523bf

diff --git a/Lib/http/client.py b/Lib/http/client.py
--- a/Lib/http/client.py
+++ b/Lib/http/client.py
@@ -147,6 +147,10 @@
 #  _is_allowed_url_pchars_re = re.compile(r"^[/!$&'()*+,;=:@%a-zA-Z0-9._~-]+$")
 # We are more lenient for assumed real world compatibility purposes.

+# These characters are not allowed within HTTP method names
+# to prevent http header injection.
+_contains_disallowed_method_pchar_re = re.compile('[\x00-\x1f]')
+
 # We always set the Content-Length header for these methods because some
 # servers will otherwise respond with a 411
 _METHODS_EXPECTING_BODY = {'PATCH', 'POST', 'PUT'}
@@ -1087,6 +1091,8 @@ def putrequest(self, method, url, skip_host=False,
         else:
             raise CannotSendRequest(self.__state)

+        self._validate_method(method)
+
         # Save the method for use later in the response phase
         self._method = method

@@ -1177,6 +1183,15 @@ def _encode_request(self, request):
         # ASCII also helps prevent CVE-2019-9740.
         return request.encode('ascii')

+    def _validate_method(self, method):
+        """Validate a method name for putrequest."""
+        # prevent http header injection
+        match = _contains_disallowed_method_pchar_re.search(method)
+        if match:
+            raise ValueError(
+                    f"method can't contain control characters. {method!r} "
+                    f"(found at least {match.group()!r})")
+
     def _validate_path(self, url):
         """Validate a url for putrequest."""
         # Prevent CVE-2019-9740.


code:
Compatibility with Python 3.8, see upstream issue
https://github.com/rbarrois/aionotify/pull/15

diff --git a/setup.py b/setup.py
index 21a554f..094de64 100755
--- a/setup.py
+++ b/setup.py
@@ -40,7 +40,7 @@ setup(
     setup_requires=[
     ],
     tests_require=[
-        'asynctest',
+        'asynctest; python_version<"3.8"',
     ],
     classifiers=[
         "Development Status :: 4 - Beta",
diff --git a/tests/test_usage.py b/tests/test_usage.py
index f156291..0476ff1 100644
--- a/tests/test_usage.py
+++ b/tests/test_usage.py
@@ -8,7 +8,11 @@ import os.path
 import tempfile
 import unittest

-import asynctest
+try:
+    testBase = unittest.IsolatedAsyncioTestCase
+except AttributeError:
+    import asynctest
+    testBase = asynctest.TestCase

 import aionotify

@@ -25,11 +29,13 @@ if AIODEBUG:
 TESTDIR = os.environ.get('AIOTESTDIR') or os.path.join(os.path.dirname(__file__), 'testevents')

-class AIONotifyTestCase(asynctest.TestCase):
+class AIONotifyTestCase(testBase):
     forbid_get_event_loop = True
     timeout = 3

     def setUp(self):
+        if not getattr (self, 'loop', None):
+            self.loop = asyncio.get_event_loop()
         if AIODEBUG:
             self.loop.set_debug(True)
         self.watcher = aionotify.Watcher()


code:
Upstream commit fixing testcases for fish>=3.1, see
https://github.com/kislyuk/argcomplete/commit/08bfc8a788e8081515d733e67be026d051c726f7

diff --git a/test/test.py b/test/test.py
index e91352b..2c34806 100755
--- a/test/test.py
+++ b/test/test.py
@@ -28,6 +28,8 @@

 BASH_VERSION = subprocess.check_output(['bash', '-c', 'echo $BASH_VERSION']).decode()
 BASH_MAJOR_VERSION = int(BASH_VERSION.split('.')[0])
+FISH_VERSION_STR = subprocess.check_output(['fish', '-c', 'echo -n $FISH_VERSION']).decode()
+FISH_VERSION_TUPLE = tuple(int(x) for x in FISH_VERSION_STR.split('.'))

 class TempDir(object):
@@ -1258,8 +1260,11 @@ class TestFish(_TestSh, unittest.TestCase):
     expected_failures = [
         'test_parse_special_characters',
         'test_comp_point',
-        'test_special_characters_double_quoted'
     ]
+    if FISH_VERSION_TUPLE < (3, 1):
+        expected_failures.extend([
+            'test_special_characters_double_quoted'
+        ])

     skipped = [
         'test_single_quotes_in_single_quotes',


code:
Patch taken from the Debian package for python-axolotl-0.1.39.
See <https://bugs.gnu.org/29415>.

Description: Removes IV paramenter from AES constructor, since it is not necessary for ctr mode.
Author: Josue Ortega <josue@debian.org>
Last-Update: 2017-04-13

--- a/axolotl/sessioncipher.py
+++ b/axolotl/sessioncipher.py
@@ -228,13 +228,7 @@
         # counterint = struct.unpack(">L", counterbytes)[0]
         # counterint = int.from_bytes(counterbytes, byteorder='big')
         ctr = Counter.new(128, initial_value=counter)
-
-        # cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
-        ivBytes = bytearray(16)
-        ByteUtil.intToByteArray(ivBytes, 0, counter)
-
-        cipher = AES.new(key, AES.MODE_CTR, IV=bytes(ivBytes), counter=ctr)
-
+        cipher = AES.new(key, AES.MODE_CTR, counter=ctr)
         return cipher


code:
From 16fbc38f13e435b4e3e1a37d706e64e05bad4691 Mon Sep 17 00:00:00 2001
From: Leo Famulari <leo@famulari.name>
Date: Tue, 10 Nov 2015 23:09:24 -0500
Subject: [PATCH] patch build to use setuptools

---
 setup.py | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/setup.py b/setup.py
index c6d57a6..27bf260 100644
--- a/setup.py
+++ b/setup.py
@@ -12,7 +12,12 @@
 # http://opensource.org/licenses/BSD-3-Clause
 import os
 import sys
-from distutils.core import setup
+
+try:
+    from setuptools import setup
+except ImportError:
+    from distutils.core import setup
+
 # a simple import wouldn't work if we moved towards a package with __init__
 from _version import __version__

--
2.6.2


code:
Patch taken from https://bugs.python.org/issue22724 and augmented with
following Nix patch
https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/interpreters/python/cpython/2.7/cross-compile.patch
to fix the whole cross-compilation circus.

---
 Makefile.pre.in | 14 +++++++-------
 configure       |  5 ++++-
 setup.py        |  9 ++++++---
 3 files changed, 17 insertions(+), 11 deletions(-)

diff --git a/Makefile.pre.in b/Makefile.pre.in
index 2a14f3323b..6239fc32fc 100644
--- a/Makefile.pre.in
+++ b/Makefile.pre.in
@@ -492,7 +492,7 @@ $(BUILDPYTHON):	Modules/python.o $(LIBRARY) $(LDLIBRARY)
 			$(BLDLIBRARY) $(LIBS) $(MODLIBS) $(SYSLIBS) $(LDLAST)

 platform: $(BUILDPYTHON) pybuilddir.txt
-	$(RUNSHARED) $(PYTHON_FOR_BUILD) -c 'import sys ; from sysconfig import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform
+	$(RUNSHARED) $(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) -c 'import sys ; from sysconfig import get_platform ; print get_platform()+"-"+sys.version[0:3]' >platform

 # Create build directory and generate the sysconfig build-time data there.
 # pybuilddir.txt contains the name of the build dir and is used for
@@ -503,7 +503,7 @@ platform: $(BUILDPYTHON) pybuilddir.txt
 # or removed in case of failure.
 pybuilddir.txt: $(BUILDPYTHON)
 	@echo "none" > ./pybuilddir.txt
-	$(RUNSHARED) $(PYTHON_FOR_BUILD) -S -m sysconfig --generate-posix-vars ;\
+	$(RUNSHARED) $(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) -S -m sysconfig --generate-posix-vars ;\
 	if test $$? -ne 0 ; then \
 		echo "generate-posix-vars failed" ; \
 		rm -f ./pybuilddir.txt ; \
@@ -525,7 +525,7 @@ sharedmods: $(BUILDPYTHON) pybuilddir.txt Modules/_math.o
 	esac; \
 	$(RUNSHARED) CC='$(CC)' LDSHARED='$(BLDSHARED)' OPT='$(OPT)' \
 		_TCLTK_INCLUDES='$(TCLTK_INCLUDES)' _TCLTK_LIBS='$(TCLTK_LIBS)' \
-		$(PYTHON_FOR_BUILD) $(srcdir)/setup.py $$quiet build
+		$(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) $(srcdir)/setup.py $$quiet build

 # Build static library
 # avoid long command lines, same as LIBRARY_OBJS
@@ -928,7 +928,7 @@ install:	@FRAMEWORKINSTALLFIRST@ commoninstall bininstall maninstall @FRAMEWORKI
 			upgrade) ensurepip="--upgrade" ;; \
 			install|*) ensurepip="" ;; \
 		esac; \
-		$(RUNSHARED) $(PYTHON_FOR_BUILD) -m ensurepip \
+		$(RUNSHARED) $(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) -m ensurepip \
 			$$ensurepip --root=$(DESTDIR)/ ; \
 	fi

@@ -939,7 +939,7 @@ altinstall:	commoninstall
 			upgrade) ensurepip="--altinstall --upgrade --no-default-pip" ;; \
 			install|*) ensurepip="--altinstall --no-default-pip" ;; \
 		esac; \
-		$(RUNSHARED) $(PYTHON_FOR_BUILD) -m ensurepip \
+		$(RUNSHARED) $(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) -m ensurepip \
 			$$ensurepip --root=$(DESTDIR)/ ; \
 	fi

@@ -1270,7 +1270,7 @@ libainstall:	@DEF_MAKE_RULE@ python-config
 # Install the dynamically loadable modules
 # This goes into $(exec_prefix)
 sharedinstall: sharedmods
-	$(RUNSHARED) $(PYTHON_FOR_BUILD) $(srcdir)/setup.py install \
+	$(RUNSHARED) $(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) $(srcdir)/setup.py install \
 	   	--prefix=$(prefix) \
 		--install-scripts=$(BINDIR) \
 		--install-platlib=$(DESTSHARED) \
@@ -1344,7 +1344,7 @@ frameworkinstallextras:
 # This installs a few of the useful scripts in Tools/scripts
 scriptsinstall:
 	SRCDIR=$(srcdir) $(RUNSHARED) \
-	$(PYTHON_FOR_BUILD) $(srcdir)/Tools/scripts/setup.py install \
+	$(PY_BUILD_ENVIRON) $(PYTHON_FOR_BUILD) $(srcdir)/Tools/scripts/setup.py install \
 	--prefix=$(prefix) \
 	--install-scripts=$(BINDIR) \
 	--root=$(DESTDIR)/
diff --git a/configure b/configure
index 67300fe2b6..6050f588c5 100755
--- a/configure
+++ b/configure
@@ -741,6 +741,7 @@ CONFIG_ARGS
 SOVERSION
 VERSION
 PYTHON_FOR_BUILD
+PY_BUILD_ENVIRON
 PYTHON_FOR_REGEN
 host_os
 host_vendor
@@ -2964,7 +2965,8 @@ $as_echo_n "checking for python interpreter for cross build... " >&6; }
 	fi
         { $as_echo "$as_me:${as_lineno-$LINENO}: result: $interp" >&5
 $as_echo "$interp" >&6; }
-	PYTHON_FOR_BUILD='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/$(PLATDIR) '$interp
+	PY_BUILD_ENVIRON='_PYTHON_PROJECT_BASE=$(abs_builddir) _PYTHON_HOST_PLATFORM=$(_PYTHON_HOST_PLATFORM) PYTHONPATH=$(shell test -f pybuilddir.txt && echo $(abs_builddir)/`cat pybuilddir.txt`:)$(srcdir)/Lib:$(srcdir)/Lib/$(PLATDIR)'
+	PYTHON_FOR_BUILD=$interp
     fi
 elif test "$cross_compiling" = maybe; then
     as_fn_error $? "Cross compiling required --host=HOST-TUPLE and --build=ARCH" "$LINENO" 5
@@ -2974,6 +2976,7 @@ fi

+
 if test "$prefix" != "/"; then
     prefix=`echo "$prefix" | sed -e 's/\/$//g'`
 fi
diff --git a/setup.py b/setup.py
index cb47a2339c..472e7e2b26 100644
--- a/setup.py
+++ b/setup.py
@@ -497,8 +497,6 @@ class PyBuildExt(build_ext):
         if not cross_compiling:
             add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib')
             add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
-        if cross_compiling:
-            self.add_gcc_paths()
         self.add_multiarch_paths()

         # Add paths specified in the environment variables LDFLAGS and
@@ -556,7 +554,10 @@ class PyBuildExt(build_ext):
         # be assumed that no additional -I,-L directives are needed.
         inc_dirs = self.compiler.include_dirs[:]
         lib_dirs = self.compiler.library_dirs[:]
-        if not cross_compiling:
+        if cross_compiling:
+            inc_dirs = []
+            lib_dirs = []
+        else:
             for d in (
                 '/usr/include',
                 ):
@@ -621,6 +622,8 @@ class PyBuildExt(build_ext):
         # Some modules that are normally always on:
         #exts.append( Extension('_weakref', ['_weakref.c']) )

+        self.compiler.library_dirs = lib_dirs + [ '.' ]
+
         # array objects
         exts.append( Extension('array', ['arraymodule.c']) )

--
2.17.1


code:
We need one patch on top of 0.3.8 for compatibility with Werkzeug 1.0.

Taken from upstream:
https://github.com/flask-restful/flask-restful/commit/73376a488907af3042b52678ac4c23f8a8911e5b

diff --git a/tests/test_api.py b/tests/test_api.py
index f7f8e661..6795d362 100644
--- a/tests/test_api.py
+++ b/tests/test_api.py
@@ -445,7 +445,9 @@ def test_handle_non_api_error(self):

         resp = app.get("/foo")
         self.assertEquals(resp.status_code, 404)
-        self.assertEquals('text/html', resp.headers['Content-Type'])
+        # in newer versions of werkzeug this is `text/html; charset=utf8`
+        content_type, _, _ = resp.headers['Content-Type'].partition(';')
+        self.assertEquals('text/html', content_type)

     def test_non_api_error_404_catchall(self):
         app = Flask(__name__)
diff --git a/tests/test_reqparse.py b/tests/test_reqparse.py
index 2f1fbedf..9776f17c 100644
--- a/tests/test_reqparse.py
+++ b/tests/test_reqparse.py
@@ -2,9 +2,9 @@
 import unittest
 from mock import Mock, patch
 from flask import Flask
-from werkzeug import exceptions, MultiDict
+from werkzeug import exceptions
 from werkzeug.wrappers import Request
-from werkzeug.datastructures import FileStorage
+from werkzeug.datastructures import FileStorage, MultiDict
 from flask_restful.reqparse import Argument, RequestParser, Namespace
 import six
 import decimal