1{ lib, stdenv, fetchFromGitHub, fetchpatch
2, bzip2
3, expat
4, libffi
5, gdbm
6, db
7, ncurses
8, openssl
9, readline
10, sqlite
11, tcl ? null, tk ? null, tix ? null, libX11 ? null, x11Support ? false
12, zlib
13, self
14, configd, coreutils
15, autoreconfHook
16, python-setup-hook
17# Some proprietary libs assume UCS2 unicode, especially on darwin :(
18, ucsEncoding ? 4
19# For the Python package set
20, packageOverrides ? (self: super: {})
21, pkgsBuildBuild
22, pkgsBuildHost
23, pkgsBuildTarget
24, pkgsHostHost
25, pkgsTargetTarget
26, sourceVersion
27, hash
28, passthruFun
29, static ? stdenv.hostPlatform.isStatic
30, stripBytecode ? reproducibleBuild
31, rebuildBytecode ? true
32, reproducibleBuild ? false
33, enableOptimizations ? false
34, strip2to3 ? false
35, stripConfig ? false
36, stripIdlelib ? false
37, stripTests ? false
38, pythonAttr ? "python${sourceVersion.major}${sourceVersion.minor}"
39}:
40
41assert x11Support -> tcl != null
42 && tk != null
43 && libX11 != null;
44
45assert lib.assertMsg (enableOptimizations -> (!stdenv.cc.isClang))
46 "Optimizations with clang are not supported. configure: error: llvm-profdata is required for a --enable-optimizations build but could not be found.";
47
48assert lib.assertMsg (reproducibleBuild -> stripBytecode)
49 "Deterministic builds require stripping bytecode.";
50
51assert lib.assertMsg (reproducibleBuild -> (!enableOptimizations))
52 "Deterministic builds are not achieved when optimizations are enabled.";
53
54assert lib.assertMsg (reproducibleBuild -> (!rebuildBytecode))
55 "Deterministic builds are not achieved when (default unoptimized) bytecode is created.";
56
57let
58 buildPackages = pkgsBuildHost;
59 inherit (passthru) pythonForBuild;
60
61 pythonForBuildInterpreter = if stdenv.hostPlatform == stdenv.buildPlatform then
62 "$out/bin/python"
63 else pythonForBuild.interpreter;
64
65 passthru = passthruFun rec {
66 inherit self sourceVersion packageOverrides;
67 implementation = "cpython";
68 libPrefix = "python${pythonVersion}";
69 executable = libPrefix;
70 pythonVersion = with sourceVersion; "${major}.${minor}";
71 sitePackages = "lib/${libPrefix}/site-packages";
72 inherit hasDistutilsCxxPatch pythonAttr;
73 pythonOnBuildForBuild = pkgsBuildBuild.${pythonAttr};
74 pythonOnBuildForHost = pkgsBuildHost.${pythonAttr};
75 pythonOnBuildForTarget = pkgsBuildTarget.${pythonAttr};
76 pythonOnHostForHost = pkgsHostHost.${pythonAttr};
77 pythonOnTargetForTarget = pkgsTargetTarget.${pythonAttr} or {};
78 } // {
79 inherit ucsEncoding;
80 };
81
82 version = with sourceVersion; "${major}.${minor}.${patch}${suffix}";
83
84 # ActiveState is a fork of cpython that includes fixes for security
85 # issues after its EOL
86 src = fetchFromGitHub {
87 owner = "ActiveState";
88 repo = "cpython";
89 rev = "v${version}";
90 inherit hash;
91 };
92
93 hasDistutilsCxxPatch = !(stdenv.cc.isGNU or false);
94 patches =
95 [ # Look in C_INCLUDE_PATH and LIBRARY_PATH for stuff.
96 ./search-path.patch
97
98 # Python recompiles a Python if the mtime stored *in* the
99 # pyc/pyo file differs from the mtime of the source file. This
100 # doesn't work in Nix because Nix changes the mtime of files in
101 # the Nix store to 1. So treat that as a special case.
102 ./nix-store-mtime.patch
103
104 # patch python to put zero timestamp into pyc
105 # if DETERMINISTIC_BUILD env var is set
106 ./deterministic-build.patch
107
108 # Fix python bug #27177 (https://bugs.python.org/issue27177)
109 # The issue is that `match.group` only recognizes python integers
110 # instead of everything that has `__index__`.
111 # This bug was fixed upstream, but not backported to 2.7
112 (fetchpatch {
113 name = "re_match_index.patch";
114 url = "https://bugs.python.org/file43084/re_match_index.patch";
115 sha256 = "0l9rw6r5r90iybdkp3hhl2pf0h0s1izc68h5d3ywrm92pq32wz57";
116 })
117
118 # Fix race-condition during pyc creation. Has a slight backwards
119 # incompatible effect: pyc symlinks will now be overridden
120 # (https://bugs.python.org/issue17222). Included in python >= 3.4,
121 # backported in debian since 2013.
122 # https://bugs.python.org/issue13146
123 ./atomic_pyc.patch
124
125 # Backport from CPython 3.8 of a good list of tests to run for PGO.
126 ./profile-task.patch
127
128 # The workaround is for unittests on Win64, which we don't support.
129 # It does break aarch64-darwin, which we do support. See:
130 # * https://bugs.python.org/issue35523
131 # * https://github.com/python/cpython/commit/e6b247c8e524
132 ../3.7/no-win64-workaround.patch
133
134 ] ++ lib.optionals (x11Support && stdenv.isDarwin) [
135 ./use-correct-tcl-tk-on-darwin.patch
136 ] ++ lib.optionals stdenv.isLinux [
137
138 # Disable the use of ldconfig in ctypes.util.find_library (since
139 # ldconfig doesn't work on NixOS), and don't use
140 # ctypes.util.find_library during the loading of the uuid module
141 # (since it will do a futile invocation of gcc (!) to find
142 # libuuid, slowing down program startup a lot).
143 ./no-ldconfig.patch
144
145 # Fix ctypes.util.find_library with gcc10.
146 ./find_library-gcc10.patch
147
148 ] ++ lib.optionals stdenv.hostPlatform.isCygwin [
149 ./2.5.2-ctypes-util-find_library.patch
150 ./2.5.2-tkinter-x11.patch
151 ./2.6.2-ssl-threads.patch
152 ./2.6.5-export-PySignal_SetWakeupFd.patch
153 ./2.6.5-FD_SETSIZE.patch
154 ./2.6.5-ncurses-abi6.patch
155 ./2.7.3-dbm.patch
156 ./2.7.3-dylib.patch
157 ./2.7.3-getpath-exe-extension.patch
158 ./2.7.3-no-libm.patch
159 ] ++ lib.optionals hasDistutilsCxxPatch [
160
161 # Patch from http://bugs.python.org/issue1222585 adapted to work with
162 # `patch -p1' and with a last hunk removed
163 # Upstream distutils is calling C compiler to compile C++ code, which
164 # only works for GCC and Apple Clang. This makes distutils to call C++
165 # compiler when needed.
166 ./python-2.7-distutils-C++.patch
167 ] ++ lib.optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
168 ./cross-compile.patch
169 ];
170
171 preConfigure = ''
172 # Purity.
173 for i in /usr /sw /opt /pkg; do
174 substituteInPlace ./setup.py --replace $i /no-such-path
175 done
176 '' + lib.optionalString (stdenv ? cc && stdenv.cc.libc != null) ''
177 for i in Lib/plat-*/regen; do
178 substituteInPlace $i --replace /usr/include/ ${stdenv.cc.libc}/include/
179 done
180 '' + lib.optionalString stdenv.isDarwin ''
181 substituteInPlace configure --replace '`/usr/bin/arch`' '"i386"'
182 substituteInPlace Lib/multiprocessing/__init__.py \
183 --replace 'os.popen(comm)' 'os.popen("${coreutils}/bin/nproc")'
184 '';
185
186 configureFlags = lib.optionals enableOptimizations [
187 "--enable-optimizations"
188 ] ++ lib.optionals (!static) [
189 "--enable-shared"
190 ] ++ [
191 "--with-threads"
192 "--with-system-ffi"
193 "--with-system-expat"
194 "--enable-unicode=ucs${toString ucsEncoding}"
195 ] ++ lib.optionals stdenv.hostPlatform.isCygwin [
196 "ac_cv_func_bind_textdomain_codeset=yes"
197 ] ++ lib.optionals stdenv.isDarwin [
198 "--disable-toolbox-glue"
199 ] ++ lib.optionals (stdenv.hostPlatform != stdenv.buildPlatform) [
200 "PYTHON_FOR_BUILD=${lib.getBin buildPackages.python}/bin/python"
201 "ac_cv_buggy_getaddrinfo=no"
202 # Assume little-endian IEEE 754 floating point when cross compiling
203 "ac_cv_little_endian_double=yes"
204 "ac_cv_big_endian_double=no"
205 "ac_cv_mixed_endian_double=no"
206 "ac_cv_x87_double_rounding=yes"
207 "ac_cv_tanh_preserves_zero_sign=yes"
208 # Generally assume that things are present and work
209 "ac_cv_posix_semaphores_enabled=yes"
210 "ac_cv_broken_sem_getvalue=no"
211 "ac_cv_wchar_t_signed=yes"
212 "ac_cv_rshift_extends_sign=yes"
213 "ac_cv_broken_nice=no"
214 "ac_cv_broken_poll=no"
215 "ac_cv_working_tzset=yes"
216 "ac_cv_have_long_long_format=yes"
217 "ac_cv_have_size_t_format=yes"
218 "ac_cv_computed_gotos=yes"
219 "ac_cv_file__dev_ptmx=yes"
220 "ac_cv_file__dev_ptc=yes"
221 ]
222 # Never even try to use lchmod on linux,
223 # don't rely on detecting glibc-isms.
224 ++ lib.optional stdenv.hostPlatform.isLinux "ac_cv_func_lchmod=no"
225 ++ lib.optional static "LDFLAGS=-static";
226
227 strictDeps = true;
228 buildInputs =
229 lib.optional (stdenv ? cc && stdenv.cc.libc != null) stdenv.cc.libc ++
230 [ bzip2 openssl zlib libffi expat db gdbm ncurses sqlite readline ]
231 ++ lib.optionals x11Support [ tcl tk libX11 ]
232 ++ lib.optional (stdenv.isDarwin && configd != null) configd;
233 nativeBuildInputs =
234 [ autoreconfHook ]
235 ++ lib.optionals (stdenv.hostPlatform != stdenv.buildPlatform)
236 [ buildPackages.stdenv.cc buildPackages.python ];
237
238 mkPaths = paths: {
239 C_INCLUDE_PATH = lib.makeSearchPathOutput "dev" "include" paths;
240 LIBRARY_PATH = lib.makeLibraryPath paths;
241 };
242
243 # Python 2.7 needs this
244 crossCompileEnv = lib.optionalAttrs (stdenv.hostPlatform != stdenv.buildPlatform)
245 { _PYTHON_HOST_PLATFORM = stdenv.hostPlatform.config; };
246
247 # Build the basic Python interpreter without modules that have
248 # external dependencies.
249
250in with passthru; stdenv.mkDerivation ({
251 pname = "python";
252 inherit version;
253
254 inherit src patches buildInputs nativeBuildInputs preConfigure configureFlags;
255
256 LDFLAGS = lib.optionalString (!stdenv.isDarwin) "-lgcc_s";
257 inherit (mkPaths buildInputs) C_INCLUDE_PATH LIBRARY_PATH;
258
259 env.NIX_CFLAGS_COMPILE = lib.optionalString (stdenv.targetPlatform.system == "x86_64-darwin") "-msse2"
260 + lib.optionalString stdenv.hostPlatform.isMusl " -DTHREAD_STACK_SIZE=0x100000";
261 DETERMINISTIC_BUILD = 1;
262
263 setupHook = python-setup-hook sitePackages;
264
265 postPatch = lib.optionalString (x11Support && (tix != null)) ''
266 substituteInPlace "Lib/lib-tk/Tix.py" --replace "os.environ.get('TIX_LIBRARY')" "os.environ.get('TIX_LIBRARY') or '${tix}/lib'"
267 '';
268
269 postInstall =
270 ''
271 # needed for some packages, especially packages that backport
272 # functionality to 2.x from 3.x
273 for item in $out/lib/${libPrefix}/test/*; do
274 if [[ "$item" != */test_support.py*
275 && "$item" != */test/support
276 && "$item" != */test/regrtest.py* ]]; then
277 rm -rf "$item"
278 else
279 echo $item
280 fi
281 done
282 touch $out/lib/${libPrefix}/test/__init__.py
283 ln -s $out/lib/${libPrefix}/pdb.py $out/bin/pdb
284 ln -s $out/lib/${libPrefix}/pdb.py $out/bin/pdb${sourceVersion.major}.${sourceVersion.minor}
285 ln -s $out/share/man/man1/{python2.7.1.gz,python.1.gz}
286
287 rm "$out"/lib/python*/plat-*/regen # refers to glibc.dev
288
289 # Determinism: Windows installers were not deterministic.
290 # We're also not interested in building Windows installers.
291 find "$out" -name 'wininst*.exe' | xargs -r rm -f
292 '' + lib.optionalString stripBytecode ''
293 # Determinism: deterministic bytecode
294 # First we delete all old bytecode.
295 find $out -name "*.pyc" -delete
296 '' + lib.optionalString rebuildBytecode ''
297 # We build 3 levels of optimized bytecode. Note the default level, without optimizations,
298 # is not reproducible yet. https://bugs.python.org/issue29708
299 # Not creating bytecode will result in a large performance loss however, so we do build it.
300 find $out -name "*.py" | ${pythonForBuildInterpreter} -m compileall -q -f -x "lib2to3" -i -
301 find $out -name "*.py" | ${pythonForBuildInterpreter} -O -m compileall -q -f -x "lib2to3" -i -
302 find $out -name "*.py" | ${pythonForBuildInterpreter} -OO -m compileall -q -f -x "lib2to3" -i -
303 '' + lib.optionalString stdenv.hostPlatform.isCygwin ''
304 cp libpython2.7.dll.a $out/lib
305 '';
306
307 inherit passthru;
308
309 postFixup = ''
310 # Include a sitecustomize.py file. Note it causes an error when it's in postInstall with 2.7.
311 cp ${../../sitecustomize.py} $out/${sitePackages}/sitecustomize.py
312 '' + lib.optionalString strip2to3 ''
313 rm -R $out/bin/2to3 $out/lib/python*/lib2to3
314 '' + lib.optionalString stripConfig ''
315 rm -R $out/bin/python*-config $out/lib/python*/config*
316 '' + lib.optionalString stripIdlelib ''
317 # Strip IDLE
318 rm -R $out/bin/idle* $out/lib/python*/idlelib
319 '' + lib.optionalString stripTests ''
320 # Strip tests
321 rm -R $out/lib/python*/test $out/lib/python*/**/test{,s}
322 '';
323
324 enableParallelBuilding = true;
325
326 doCheck = false; # expensive, and fails
327
328 meta = {
329 homepage = "http://python.org";
330 description = "A high-level dynamically-typed programming language";
331 longDescription = ''
332 Python is a remarkably powerful dynamic programming language that
333 is used in a wide variety of application domains. Some of its key
334 distinguishing features include: clear, readable syntax; strong
335 introspection capabilities; intuitive object orientation; natural
336 expression of procedural code; full modularity, supporting
337 hierarchical packages; exception-based error handling; and very
338 high level dynamic data types.
339 '';
340 license = lib.licenses.psfl;
341 platforms = lib.platforms.all;
342 maintainers = with lib.maintainers; [ fridh thiagokokada ];
343 knownVulnerabilities = [
344 "Python 2.7 has reached its end of life after 2020-01-01. See https://www.python.org/doc/sunset-python-2/."
345 # Quote: That means that we will not improve it anymore after that day,
346 # even if someone finds a security problem in it. You should upgrade to
347 # Python 3 as soon as you can. [..] So, in 2008, we announced that we
348 # would sunset Python 2 in 2015, and asked people to upgrade before
349 # then. Some did, but many did not. So, in 2014, we extended that
350 # sunset till 2020.
351 ];
352 };
353 } // crossCompileEnv)