-
-
Notifications
You must be signed in to change notification settings - Fork 145
/
build.py
2046 lines (1742 loc) · 67.6 KB
/
build.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
import argparse
import concurrent.futures
import io
import json
import multiprocessing
import os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
from pythonbuild.cpython import (
STDLIB_TEST_PACKAGES,
meets_python_maximum_version,
meets_python_minimum_version,
parse_config_c,
)
from pythonbuild.downloads import DOWNLOADS
from pythonbuild.utils import (
compress_python_archive,
create_tar_from_directory,
download_entry,
extract_tar_to_directory,
extract_zip_to_directory,
normalize_tar_archive,
release_tag_from_git,
validate_python_json,
)
ROOT = pathlib.Path(os.path.abspath(__file__)).parent.parent
BUILD = ROOT / "build"
DIST = ROOT / "dist"
SUPPORT = ROOT / "cpython-windows"
LOG_PREFIX = [None]
LOG_FH = [None]
# Extensions that need to be converted from standalone to built-in.
# Key is name of VS project representing the standalone extension.
# Value is dict describing the extension.
CONVERT_TO_BUILTIN_EXTENSIONS = {
"_asyncio": {
# _asynciomodule.c is included in pythoncore for some reason.
# This was fixed in Python 3.9. See hacky code for
# `honor_allow_missing_preprocessor`.
"allow_missing_preprocessor": True
},
"_bz2": {},
"_ctypes": {
"shared_depends": ["libffi-8"],
},
"_decimal": {},
"_elementtree": {},
"_hashlib": {
"shared_depends_amd64": ["libcrypto-1_1-x64"],
"shared_depends_win32": ["libcrypto-1_1"],
},
"_lzma": {
"ignore_additional_depends": {"$(OutDir)liblzma$(PyDebugExt).lib"},
},
"_msi": {
# Removed in 3.13.
"ignore_missing": True,
},
"_overlapped": {},
"_multiprocessing": {},
"_socket": {},
"_sqlite3": {"shared_depends": ["sqlite3"]},
# See the one-off calls to copy_link_to_lib() and elsewhere to hack up
# project files.
"_ssl": {
"shared_depends_amd64": ["libcrypto-1_1-x64", "libssl-1_1-x64"],
"shared_depends_win32": ["libcrypto-1_1", "libssl-1_1"],
},
"_tkinter": {
"shared_depends": ["tcl86t", "tk86t"],
},
"_queue": {},
"_uuid": {"ignore_missing": True},
"_wmi": {
# Introduced in 3.12.
"ignore_missing": True,
},
"_zoneinfo": {"ignore_missing": True},
"pyexpat": {},
"select": {},
"unicodedata": {},
"winsound": {},
}
REQUIRED_EXTENSIONS = {
"_codecs",
"_io",
"_signal",
"_thread",
"_tracemalloc",
"_weakref",
"faulthandler",
}
# Used to annotate licenses.
EXTENSION_TO_LIBRARY_DOWNLOADS_ENTRY = {
"_bz2": ["bzip2"],
"_ctypes": ["libffi"],
"_hashlib": ["openssl"],
"_lzma": ["xz"],
"_sqlite3": ["sqlite"],
"_ssl": ["openssl"],
"_tkinter": ["tcl", "tk", "tix"],
"_uuid": ["uuid"],
"zlib": ["zlib"],
}
# Tests to run during PGO profiling.
#
# This set was copied from test.libregrtest.pgo in the CPython source
# distribution.
PGO_TESTS = {
"test_array",
"test_base64",
"test_binascii",
"test_binop",
"test_bisect",
"test_bytes",
"test_bz2",
"test_cmath",
"test_codecs",
"test_collections",
"test_complex",
"test_dataclasses",
"test_datetime",
"test_decimal",
"test_difflib",
"test_embed",
"test_float",
"test_fstring",
"test_functools",
"test_generators",
"test_hashlib",
"test_heapq",
"test_int",
"test_itertools",
"test_json",
"test_long",
"test_lzma",
"test_math",
"test_memoryview",
"test_operator",
"test_ordered_dict",
"test_pickle",
"test_pprint",
"test_re",
"test_set",
# Renamed to test_sqlite3 in 3.11. We keep both names as we just look for
# test presence in this set.
"test_sqlite",
"test_sqlite3",
"test_statistics",
"test_struct",
"test_tabnanny",
"test_time",
"test_unicode",
"test_xml_etree",
"test_xml_etree_c",
}
def log(msg):
if isinstance(msg, bytes):
msg_str = msg.decode("utf-8", "replace")
msg_bytes = msg
else:
msg_str = msg
msg_bytes = msg.encode("utf-8", "replace")
print("%s> %s" % (LOG_PREFIX[0], msg_str))
if LOG_FH[0]:
LOG_FH[0].write(msg_bytes + b"\n")
LOG_FH[0].flush()
def exec_and_log(args, cwd, env, exit_on_error=True):
log("executing %s" % " ".join(args))
p = subprocess.Popen(
args,
cwd=cwd,
env=env,
bufsize=1,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
)
for line in iter(p.stdout.readline, b""):
log(line.rstrip())
p.wait()
log("process exited %d" % p.returncode)
if p.returncode and exit_on_error:
sys.exit(p.returncode)
def find_vswhere():
vswhere = (
pathlib.Path(os.environ["ProgramFiles(x86)"])
/ "Microsoft Visual Studio"
/ "Installer"
/ "vswhere.exe"
)
if not vswhere.exists():
print("%s does not exist" % vswhere)
sys.exit(1)
return vswhere
def find_vs_path(path, msvc_version):
vswhere = find_vswhere()
if msvc_version == "2019":
version = "[16,17)"
elif msvc_version == "2022":
version = "[17,18)"
else:
raise ValueError(f"unsupported Visual Studio version: {msvc_version}")
p = subprocess.check_output(
[
str(vswhere),
# Visual Studio 2019.
"-version",
version,
"-property",
"installationPath",
"-products",
"*",
]
)
# Strictly speaking the output may not be UTF-8.
p = pathlib.Path(p.strip().decode("utf-8"))
p = p / path
if not p.exists():
print("%s does not exist" % p)
sys.exit(1)
return p
def find_msbuild(msvc_version):
return find_vs_path(
pathlib.Path("MSBuild") / "Current" / "Bin" / "MSBuild.exe", msvc_version
)
def find_vcvarsall_path(msvc_version):
"""Find path to vcvarsall.bat"""
return find_vs_path(
pathlib.Path("VC") / "Auxiliary" / "Build" / "vcvarsall.bat", msvc_version
)
class NoSearchStringError(Exception):
"""Represents a missing search string when replacing content in a file."""
def static_replace_in_file(p: pathlib.Path, search, replace):
"""Replace occurrences of a string in a file.
The updated file contents are written out in place.
"""
with p.open("rb") as fh:
data = fh.read()
# Build should be as deterministic as possible. Assert that wanted changes
# actually occur.
if search not in data:
raise NoSearchStringError("search string (%s) not in %s" % (search, p))
log("replacing `%s` with `%s` in %s" % (search, replace, p))
data = data.replace(search, replace)
with p.open("wb") as fh:
fh.write(data)
OPENSSL_PROPS_REMOVE_RULES_LEGACY = b"""
<ItemGroup>
<_SSLDLL Include="$(opensslOutDir)\libcrypto$(_DLLSuffix).dll" />
<_SSLDLL Include="$(opensslOutDir)\libcrypto$(_DLLSuffix).pdb" />
<_SSLDLL Include="$(opensslOutDir)\libssl$(_DLLSuffix).dll" />
<_SSLDLL Include="$(opensslOutDir)\libssl$(_DLLSuffix).pdb" />
</ItemGroup>
<Target Name="_CopySSLDLL" Inputs="@(_SSLDLL)" Outputs="@(_SSLDLL->'$(OutDir)%(Filename)%(Extension)')" AfterTargets="Build">
<Copy SourceFiles="@(_SSLDLL)" DestinationFolder="$(OutDir)" />
</Target>
<Target Name="_CleanSSLDLL" BeforeTargets="Clean">
<Delete Files="@(_SSLDLL->'$(OutDir)%(Filename)%(Extension)')" TreatErrorsAsWarnings="true" />
</Target>
"""
OPENSSL_PROPS_REMOVE_RULES = b"""
<ItemGroup>
<_SSLDLL Include="$(opensslOutDir)\libcrypto$(_DLLSuffix).dll" />
<_SSLDLL Include="$(opensslOutDir)\libcrypto$(_DLLSuffix).pdb" />
<_SSLDLL Include="$(opensslOutDir)\libssl$(_DLLSuffix).dll" />
<_SSLDLL Include="$(opensslOutDir)\libssl$(_DLLSuffix).pdb" />
</ItemGroup>
<Target Name="_CopySSLDLL"
Inputs="@(_SSLDLL)"
Outputs="@(_SSLDLL->'$(OutDir)%(Filename)%(Extension)')"
Condition="$(SkipCopySSLDLL) == ''"
AfterTargets="Build">
<Copy SourceFiles="@(_SSLDLL)" DestinationFolder="$(OutDir)" />
</Target>
<Target Name="_CleanSSLDLL" Condition="$(SkipCopySSLDLL) == ''" BeforeTargets="Clean">
<Delete Files="@(_SSLDLL->'$(OutDir)%(Filename)%(Extension)')" TreatErrorsAsWarnings="true" />
</Target>
"""
LIBFFI_PROPS_REMOVE_RULES = b"""
<Target Name="_CopyLIBFFIDLL" Inputs="@(_LIBFFIDLL)" Outputs="@(_LIBFFIDLL->'$(OutDir)%(Filename)%(Extension)')" AfterTargets="Build">
<Copy SourceFiles="@(_LIBFFIDLL)" DestinationFolder="$(OutDir)" />
</Target>
"""
def hack_props(
td: pathlib.Path,
pcbuild_path: pathlib.Path,
arch: str,
):
# TODO can we pass props into msbuild.exe?
# Our dependencies are in different directories from what CPython's
# build system expects. Modify the config file appropriately.
bzip2_version = DOWNLOADS["bzip2"]["version"]
sqlite_version = DOWNLOADS["sqlite"]["version"]
xz_version = DOWNLOADS["xz"]["version"]
zlib_version = DOWNLOADS["zlib"]["version"]
tcltk_commit = DOWNLOADS["tk-windows-bin"]["git_commit"]
mpdecimal_version = DOWNLOADS["mpdecimal"]["version"]
sqlite_path = td / ("sqlite-autoconf-%s" % sqlite_version)
bzip2_path = td / ("bzip2-%s" % bzip2_version)
libffi_path = td / "libffi"
tcltk_path = td / ("cpython-bin-deps-%s" % tcltk_commit)
xz_path = td / ("xz-%s" % xz_version)
zlib_path = td / ("zlib-%s" % zlib_version)
mpdecimal_path = td / ("mpdecimal-%s" % mpdecimal_version)
openssl_root = td / "openssl" / arch
openssl_libs_path = openssl_root / "lib"
openssl_include_path = openssl_root / "include"
python_props_path = pcbuild_path / "python.props"
lines = []
with python_props_path.open("rb") as fh:
for line in fh:
line = line.rstrip()
# The syntax of these lines changed in 3.10+. 3.10 backport commit
# 3139ea33ed84190e079d6ff4859baccdad778dae. Once we drop support for
# Python 3.9 we can pass these via properties instead of editing the
# properties file.
if b"<bz2Dir" in line:
line = b"<bz2Dir>%s\\</bz2Dir>" % bzip2_path
elif b"<libffiOutDir" in line:
line = b"<libffiOutDir>%s\\</libffiOutDir>" % libffi_path
elif b"<lzmaDir" in line:
line = b"<lzmaDir>%s\\</lzmaDir>" % xz_path
elif b"<opensslIncludeDir" in line:
line = (
b"<opensslIncludeDir>%s</opensslIncludeDir>" % openssl_include_path
)
elif b"<opensslOutDir" in line:
line = b"<opensslOutDir>%s\\</opensslOutDir>" % openssl_libs_path
elif b"<sqlite3Dir" in line:
line = b"<sqlite3Dir>%s\\</sqlite3Dir>" % sqlite_path
elif b"<zlibDir" in line:
line = b"<zlibDir>%s\\</zlibDir>" % zlib_path
elif b"<mpdecimalDir" in line:
line = b"<mpdecimalDir>%s\\</mpdecimalDir>" % mpdecimal_path
lines.append(line)
with python_props_path.open("wb") as fh:
fh.write(b"\n".join(lines))
tcltkprops_path = pcbuild_path / "tcltk.props"
# Later versions of 3.10 and 3.11 enabled support for defining paths via properties.
# See CPython commit 3139ea33ed84190e079d6ff4859baccdad778dae.
# Once we drop support for CPython 3.9 we can replace this with passing properties.
try:
static_replace_in_file(
tcltkprops_path,
rb"""<tcltkDir Condition="$(tcltkDir) == ''">$(ExternalsDir)tcltk-$(TclVersion)\$(ArchName)\</tcltkDir>""",
rb"<tcltkDir>%s\$(ArchName)\</tcltkDir>" % tcltk_path,
)
except NoSearchStringError:
static_replace_in_file(
tcltkprops_path,
rb"<tcltkDir>$(ExternalsDir)tcltk-$(TclMajorVersion).$(TclMinorVersion).$(TclPatchLevel).$(TclRevision)\$(ArchName)\</tcltkDir>",
rb"<tcltkDir>%s\$(ArchName)\</tcltkDir>" % tcltk_path,
)
# We want to statically link against OpenSSL. This requires using our own
# OpenSSL build. This requires some hacking of various files.
openssl_props = pcbuild_path / "openssl.props"
if arch == "amd64":
suffix = b"-x64"
elif arch == "win32":
suffix = b""
elif arch == "arm64":
suffix = b""
else:
raise Exception("unhandled architecture: %s" % arch)
try:
# CPython 3.11+ builds with OpenSSL 3.0 by default.
static_replace_in_file(
openssl_props,
b"<_DLLSuffix>-3</_DLLSuffix>",
b"<_DLLSuffix>-3%s</_DLLSuffix>" % suffix,
)
except NoSearchStringError:
static_replace_in_file(
openssl_props,
b"<_DLLSuffix>-1_1</_DLLSuffix>",
b"<_DLLSuffix>-1_1%s</_DLLSuffix>" % suffix,
)
libffi_props = pcbuild_path / "libffi.props"
# Always use libffi-8 / 3.4.2. (Python < 3.11 use libffi-7 by default.)
try:
static_replace_in_file(
libffi_props,
rb"""<_LIBFFIDLL Include="$(libffiOutDir)\libffi-7.dll" />""",
rb"""<_LIBFFIDLL Include="$(libffiOutDir)\libffi-8.dll" />""",
)
static_replace_in_file(
libffi_props,
rb"<AdditionalDependencies>libffi-7.lib;%(AdditionalDependencies)</AdditionalDependencies>",
rb"<AdditionalDependencies>libffi-8.lib;%(AdditionalDependencies)</AdditionalDependencies>",
)
except NoSearchStringError:
pass
def hack_project_files(
td: pathlib.Path,
cpython_source_path: pathlib.Path,
build_directory: str,
python_version: str,
):
"""Hacks Visual Studio project files to work with our build."""
pcbuild_path = cpython_source_path / "PCbuild"
hack_props(
td,
pcbuild_path,
build_directory,
)
# Our SQLite directory is named weirdly. This throws off version detection
# in the project file. Replace the parsing logic with a static string.
sqlite3_version = DOWNLOADS["sqlite"]["actual_version"].encode("ascii")
sqlite3_version_parts = sqlite3_version.split(b".")
sqlite3_path = pcbuild_path / "sqlite3.vcxproj"
static_replace_in_file(
sqlite3_path,
rb"<_SqliteVersion>$([System.Text.RegularExpressions.Regex]::Match(`$(sqlite3Dir)`, `((\d+)\.(\d+)\.(\d+)\.(\d+))\\?$`).Groups)</_SqliteVersion>",
rb"<_SqliteVersion>%s</_SqliteVersion>" % sqlite3_version,
)
static_replace_in_file(
sqlite3_path,
rb"<SqliteVersion>$(_SqliteVersion.Split(`;`)[1])</SqliteVersion>",
rb"<SqliteVersion>%s</SqliteVersion>" % sqlite3_version,
)
static_replace_in_file(
sqlite3_path,
rb"<SqliteMajorVersion>$(_SqliteVersion.Split(`;`)[2])</SqliteMajorVersion>",
rb"<SqliteMajorVersion>%s</SqliteMajorVersion>" % sqlite3_version_parts[0],
)
static_replace_in_file(
sqlite3_path,
rb"<SqliteMinorVersion>$(_SqliteVersion.Split(`;`)[3])</SqliteMinorVersion>",
rb"<SqliteMinorVersion>%s</SqliteMinorVersion>" % sqlite3_version_parts[1],
)
static_replace_in_file(
sqlite3_path,
rb"<SqliteMicroVersion>$(_SqliteVersion.Split(`;`)[4])</SqliteMicroVersion>",
rb"<SqliteMicroVersion>%s</SqliteMicroVersion>" % sqlite3_version_parts[2],
)
static_replace_in_file(
sqlite3_path,
rb"<SqlitePatchVersion>$(_SqliteVersion.Split(`;`)[5])</SqlitePatchVersion>",
rb"<SqlitePatchVersion>%s</SqlitePatchVersion>" % sqlite3_version_parts[3],
)
# Our version of the xz sources is newer than what's in cpython-source-deps
# and the xz sources changed the path to config.h. Hack the project file
# accordingly.
#
# ... but CPython finally upgraded liblzma in 2022, so newer CPython releases
# already have this patch. So we're phasing it out.
try:
liblzma_path = pcbuild_path / "liblzma.vcxproj"
static_replace_in_file(
liblzma_path,
rb"$(lzmaDir)windows;$(lzmaDir)src/liblzma/common;",
rb"$(lzmaDir)windows\vs2019;$(lzmaDir)src/liblzma/common;",
)
static_replace_in_file(
liblzma_path,
rb'<ClInclude Include="$(lzmaDir)windows\config.h" />',
rb'<ClInclude Include="$(lzmaDir)windows\vs2019\config.h" />',
)
except NoSearchStringError:
pass
# Our logic for rewriting extension projects gets confused by _sqlite.vcxproj not
# having a `<PreprocessorDefinitions>` line in 3.10+. So adjust that.
try:
static_replace_in_file(
pcbuild_path / "_sqlite3.vcxproj",
rb"<AdditionalIncludeDirectories>$(sqlite3Dir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>",
b"<AdditionalIncludeDirectories>$(sqlite3Dir);%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>\r\n <PreprocessorDefinitions>%(PreprocessorDefinitions)</PreprocessorDefinitions>",
)
except NoSearchStringError:
pass
# Our custom OpenSSL build has applink.c in a different location
# from the binary OpenSSL distribution. Update it.
ssl_proj = pcbuild_path / "_ssl.vcxproj"
static_replace_in_file(
ssl_proj,
rb'<ClCompile Include="$(opensslIncludeDir)\applink.c">',
rb'<ClCompile Include="$(opensslIncludeDir)\openssl\applink.c">',
)
# We're still on the pre-built tk-windows-bin 8.6.12 which doesn't have a
# standalone zlib DLL. So remove references to it from 3.12+.
if meets_python_minimum_version(python_version, "3.12"):
static_replace_in_file(
pcbuild_path / "_tkinter.vcxproj",
rb'<_TclTkDLL Include="$(tcltkdir)\bin\$(tclZlibDllName)" />',
rb"",
)
# We don't need to produce python_uwp.exe and its *w variant. Or the
# python3.dll, pyshellext, or pylauncher.
# Cut them from the build to save time and so their presence doesn't
# interfere with packaging up the build artifacts.
pcbuild_proj = pcbuild_path / "pcbuild.proj"
static_replace_in_file(
pcbuild_proj,
b'<Projects2 Include="python_uwp.vcxproj;pythonw_uwp.vcxproj" Condition="$(IncludeUwp)" />',
b"",
)
static_replace_in_file(
pcbuild_proj,
b'<Projects Include="pylauncher.vcxproj;pywlauncher.vcxproj" />',
b"",
)
static_replace_in_file(
pcbuild_proj, b'<Projects Include="pyshellext.vcxproj" />', b""
)
# Ditto for freeze_importlib, which isn't needed since we don't modify
# the frozen importlib baked into the source distribution (
# Python/importlib.h and Python/importlib_external.h).
#
# But Python 3.11 refactored the frozen module project handling and if
# we attempt to disable this project there we get a build failure due to
# a missing /Python/frozen_modules/getpath.h file. So we skip this on
# newer Python.
try:
static_replace_in_file(
pcbuild_proj,
b"""<Projects2 Condition="$(Platform) != 'ARM' and $(Platform) != 'ARM64'" Include="_freeze_importlib.vcxproj" />""",
b"",
)
except NoSearchStringError:
pass
PYPORT_EXPORT_SEARCH_39 = b"""
#if defined(__CYGWIN__)
# define HAVE_DECLSPEC_DLL
#endif
#include "exports.h"
/* only get special linkage if built as shared or platform is Cygwin */
#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
# if defined(HAVE_DECLSPEC_DLL)
# if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
# define PyAPI_FUNC(RTYPE) Py_EXPORTED_SYMBOL RTYPE
# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC PyObject*
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to those described at the bottom of 4.1: */
/* http://docs.python.org/extending/windows.html#a-cookbook-approach */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) Py_IMPORTED_SYMBOL RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern Py_IMPORTED_SYMBOL RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC_DLL */
#endif /* Py_ENABLE_SHARED */
/* If no external linkage macros defined by now, create defaults */
#ifndef PyAPI_FUNC
# define PyAPI_FUNC(RTYPE) Py_EXPORTED_SYMBOL RTYPE
#endif
#ifndef PyAPI_DATA
# define PyAPI_DATA(RTYPE) extern Py_EXPORTED_SYMBOL RTYPE
#endif
#ifndef PyMODINIT_FUNC
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" Py_EXPORTED_SYMBOL PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC Py_EXPORTED_SYMBOL PyObject*
# endif /* __cplusplus */
#endif
"""
PYPORT_EXPORT_SEARCH_38 = b"""
#if defined(__CYGWIN__)
# define HAVE_DECLSPEC_DLL
#endif
/* only get special linkage if built as shared or platform is Cygwin */
#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
# if defined(HAVE_DECLSPEC_DLL)
# if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC PyObject*
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to those described at the bottom of 4.1: */
/* http://docs.python.org/extending/windows.html#a-cookbook-approach */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC_DLL */
#endif /* Py_ENABLE_SHARED */
/* If no external linkage macros defined by now, create defaults */
#ifndef PyAPI_FUNC
# define PyAPI_FUNC(RTYPE) RTYPE
#endif
#ifndef PyAPI_DATA
# define PyAPI_DATA(RTYPE) extern RTYPE
#endif
#ifndef PyMODINIT_FUNC
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC PyObject*
# endif /* __cplusplus */
#endif
"""
PYPORT_EXPORT_SEARCH_37 = b"""
#if defined(__CYGWIN__)
# define HAVE_DECLSPEC_DLL
#endif
/* only get special linkage if built as shared or platform is Cygwin */
#if defined(Py_ENABLE_SHARED) || defined(__CYGWIN__)
# if defined(HAVE_DECLSPEC_DLL)
# if defined(Py_BUILD_CORE) || defined(Py_BUILD_CORE_BUILTIN)
# define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
# define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
/* module init functions inside the core need no external linkage */
/* except for Cygwin to handle embedding */
# if defined(__CYGWIN__)
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# else /* __CYGWIN__ */
# define PyMODINIT_FUNC PyObject*
# endif /* __CYGWIN__ */
# else /* Py_BUILD_CORE */
/* Building an extension module, or an embedded situation */
/* public Python functions and data are imported */
/* Under Cygwin, auto-import functions to prevent compilation */
/* failures similar to those described at the bottom of 4.1: */
/* http://docs.python.org/extending/windows.html#a-cookbook-approach */
# if !defined(__CYGWIN__)
# define PyAPI_FUNC(RTYPE) __declspec(dllimport) RTYPE
# endif /* !__CYGWIN__ */
# define PyAPI_DATA(RTYPE) extern __declspec(dllimport) RTYPE
/* module init functions outside the core must be exported */
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" __declspec(dllexport) PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC __declspec(dllexport) PyObject*
# endif /* __cplusplus */
# endif /* Py_BUILD_CORE */
# endif /* HAVE_DECLSPEC_DLL */
#endif /* Py_ENABLE_SHARED */
/* If no external linkage macros defined by now, create defaults */
#ifndef PyAPI_FUNC
# define PyAPI_FUNC(RTYPE) RTYPE
#endif
#ifndef PyAPI_DATA
# define PyAPI_DATA(RTYPE) extern RTYPE
#endif
#ifndef PyMODINIT_FUNC
# if defined(__cplusplus)
# define PyMODINIT_FUNC extern "C" PyObject*
# else /* __cplusplus */
# define PyMODINIT_FUNC PyObject*
# endif /* __cplusplus */
#endif
"""
PYPORT_EXPORT_REPLACE_NEW = b"""
#include "exports.h"
#define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
#define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
#define PyMODINIT_FUNC __declspec(dllexport) PyObject*
"""
PYPORT_EXPORT_REPLACE_OLD = b"""
#define PyAPI_FUNC(RTYPE) __declspec(dllexport) RTYPE
#define PyAPI_DATA(RTYPE) extern __declspec(dllexport) RTYPE
#define PyMODINIT_FUNC __declspec(dllexport) PyObject*
"""
CTYPES_INIT_REPLACE = b"""
if _os.name == "nt":
pythonapi = PyDLL("python dll", None, _sys.dllhandle)
elif _sys.platform == "cygwin":
pythonapi = PyDLL("libpython%d.%d.dll" % _sys.version_info[:2])
else:
pythonapi = PyDLL(None)
"""
SYSMODULE_WINVER_SEARCH = b"""
#ifdef MS_COREDLL
SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
#endif
"""
SYSMODULE_WINVER_REPLACE = b"""
#ifdef MS_COREDLL
SET_SYS("dllhandle", PyLong_FromVoidPtr(PyWin_DLLhModule));
SET_SYS_FROM_STRING("winver", PyWin_DLLVersionString);
#else
SET_SYS_FROM_STRING("winver", "%s");
#endif
"""
SYSMODULE_WINVER_SEARCH_38 = b"""
#ifdef MS_COREDLL
SET_SYS_FROM_STRING("dllhandle",
PyLong_FromVoidPtr(PyWin_DLLhModule));
SET_SYS_FROM_STRING("winver",
PyUnicode_FromString(PyWin_DLLVersionString));
#endif
"""
SYSMODULE_WINVER_REPLACE_38 = b"""
#ifdef MS_COREDLL
SET_SYS_FROM_STRING("dllhandle",
PyLong_FromVoidPtr(PyWin_DLLhModule));
SET_SYS_FROM_STRING("winver",
PyUnicode_FromString(PyWin_DLLVersionString));
#else
SET_SYS_FROM_STRING("winver", PyUnicode_FromString("%s"));
#endif
"""
def run_msbuild(
msbuild: pathlib.Path,
pcbuild_path: pathlib.Path,
configuration: str,
platform: str,
python_version: str,
windows_sdk_version: str,
freethreaded: bool,
):
args = [
str(msbuild),
str(pcbuild_path / "pcbuild.proj"),
"/target:Build",
"/property:Configuration=%s" % configuration,
"/property:Platform=%s" % platform,
"/maxcpucount",
"/nologo",
"/verbosity:normal",
"/property:IncludeExternals=true",
"/property:IncludeSSL=true",
"/property:IncludeTkinter=true",
"/property:IncludeTests=true",
"/property:OverrideVersion=%s" % python_version,
"/property:IncludeCTypes=true",
# We pin the Windows 10 SDK version to make builds more deterministic.
# This can also work around known incompatibilities with the Windows 11
# SDK as of at least CPython 3.9.7.
f"/property:DefaultWindowsSDKVersion={windows_sdk_version}",
]
if freethreaded:
args.append("/property:DisableGil=true")
exec_and_log(args, str(pcbuild_path), os.environ)
def build_openssl_for_arch(
perl_path,
arch: str,
openssl_archive,
openssl_version: str,
nasm_archive,
build_root: pathlib.Path,
*,
jom_archive,
):
nasm_version = DOWNLOADS["nasm-windows-bin"]["version"]
log("extracting %s to %s" % (openssl_archive, build_root))
extract_tar_to_directory(openssl_archive, build_root)
log("extracting %s to %s" % (nasm_archive, build_root))
extract_tar_to_directory(nasm_archive, build_root)
log("extracting %s to %s" % (jom_archive, build_root))
extract_zip_to_directory(jom_archive, build_root / "jom")
nasm_path = build_root / ("cpython-bin-deps-nasm-%s" % nasm_version)
jom_path = build_root / "jom"
env = dict(os.environ)
# Add Perl and nasm paths to front of PATH.
env["PATH"] = "%s;%s;%s;%s" % (perl_path.parent, nasm_path, jom_path, env["PATH"])
source_root = build_root / ("openssl-%s" % openssl_version)
# uplink.c tries to find the OPENSSL_Applink function exported from the current
# executable. However, it is exported from _ssl[_d].pyd in shared builds. So
# update its sounce to look for it from there.
static_replace_in_file(
source_root / "ms" / "uplink.c",
b"((h = GetModuleHandle(NULL)) == NULL)",
b'((h = GetModuleHandleA("_ssl.pyd")) == NULL) if ((h = GetModuleHandleA("_ssl_d.pyd")) == NULL) if ((h = GetModuleHandle(NULL)) == NULL)',
)
if arch == "x86":
configure = "VC-WIN32"
prefix = "32"
elif arch == "amd64":
configure = "VC-WIN64A"
prefix = "64"
elif arch == "arm64":
configure = "VC-WIN64-ARM"
prefix = "arm64"
else:
raise Exception("unhandled architecture: %s" % arch)
# The official CPython OpenSSL builds hack ms/uplink.c to change the
# ``GetModuleHandle(NULL)`` invocation to load things from _ssl.pyd
# instead. But since we statically link the _ssl extension, this hackery
# is not required.
# Set DESTDIR to affect install location.
dest_dir = build_root / "install"
env["DESTDIR"] = str(dest_dir)
install_root = dest_dir / prefix
exec_and_log(
[
str(perl_path),
"Configure",
configure,
"no-idea",
"no-mdc2",
"no-tests",
"--prefix=/%s" % prefix,
],
source_root,
{
**env,
"CFLAGS": env.get("CFLAGS", "") + " /FS",
},
)
# exec_and_log(["nmake"], source_root, env)
exec_and_log(
[str(jom_path / "jom"), "/J", str(multiprocessing.cpu_count())],
source_root,
env,
)
# We don't care about accessory files, docs, etc. So just run `install_sw`
# target to get the main files.
exec_and_log(["nmake", "install_sw"], source_root, env)
# Copy the _static libraries as well.
for l in ("crypto", "ssl"):
basename = "lib%s_static.lib" % l
source = source_root / basename
dest = install_root / "lib" / basename
log("copying %s to %s" % (source, dest))
shutil.copyfile(source, dest)
# Copy `applink.c` to the include directory.
source_applink = source_root / "ms" / "applink.c"
dest_applink = install_root / "include" / "openssl" / "applink.c"
log("copying %s to %s" % (source_applink, dest_applink))
shutil.copyfile(source_applink, dest_applink)
def build_openssl(
entry: str,
perl_path: pathlib.Path,
arch: str,
dest_archive: pathlib.Path,
):
"""Build OpenSSL from sources using the Perl executable specified."""
openssl_version = DOWNLOADS[entry]["version"]
# First ensure the dependencies are in place.
openssl_archive = download_entry(entry, BUILD)
nasm_archive = download_entry("nasm-windows-bin", BUILD)
jom_archive = download_entry("jom-windows-bin", BUILD)
with tempfile.TemporaryDirectory(prefix="openssl-build-") as td:
td = pathlib.Path(td)
root_32 = td / "x86"
root_64 = td / "x64"