forked from astral-sh/python-build-standalone
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.py
2512 lines (2088 loc) · 84.8 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 os
import pathlib
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
import multiprocessing
from pythonbuild.downloads import DOWNLOADS
from pythonbuild.cpython import parse_config_c, STDLIB_TEST_PACKAGES
from pythonbuild.utils import (
create_tar_from_directory,
download_entry,
extract_tar_to_directory,
extract_zip_to_directory,
compress_python_archive,
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-7"],
"static_depends_no_project": ["libffi"],
},
"_decimal": {},
"_elementtree": {},
"_hashlib": {
"shared_depends_amd64": ["libcrypto-1_1-x64"],
"shared_depends_win32": ["libcrypto-1_1"],
},
"_lzma": {
"ignore_additional_depends": {"$(OutDir)liblzma$(PyDebugExt).lib"},
"static_depends": ["liblzma"],
},
"_msi": {},
"_overlapped": {},
"_multiprocessing": {},
"_socket": {},
"_sqlite3": {"shared_depends": ["sqlite3"], "static_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"],
"static_depends_no_project": ["libcrypto_static", "libssl_static"],
},
"_tkinter": {"ignore_static": True, "shared_depends": ["tcl86t", "tk86t"],},
"_queue": {},
"_uuid": {"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",
"test_sqlite",
"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):
vswhere = find_vswhere()
p = subprocess.check_output(
[
str(vswhere),
# Visual Studio 2019.
"-version",
"[16,17)",
"-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():
return find_vs_path(pathlib.Path("MSBuild") / "Current" / "Bin" / "MSBuild.exe")
def find_vcvarsall_path():
"""Find path to vcvarsall.bat"""
return find_vs_path(pathlib.Path("VC") / "Auxiliary" / "Build" / "vcvarsall.bat")
def find_vctools_path():
vswhere = find_vswhere()
p = subprocess.check_output(
[
str(vswhere),
"-latest",
"-products",
"*",
"-requires",
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
"-property",
"installationPath",
]
)
# Strictly speaking the output may not be UTF-8.
p = pathlib.Path(p.strip().decode("utf-8"))
version_path = (
p / "VC" / "Auxiliary" / "Build" / "Microsoft.VCToolsVersion.default.txt"
)
with version_path.open("r", encoding="utf-8") as fh:
tools_version = fh.read().strip()
tools_path = p / "VC" / "Tools" / "MSVC" / tools_version / "bin" / "Hostx64" / "x64"
if not tools_path.exists():
print("%s does not exist" % tools_path)
sys.exit(1)
return tools_path
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)
def add_to_config_c(source_path: pathlib.Path, extension: str, init_fn: str):
"""Add an extension to PC/config.c"""
config_c_path = source_path / "PC" / "config.c"
lines = []
with config_c_path.open("r", encoding="utf8") as fh:
for line in fh:
line = line.rstrip()
# Insert the init function declaration before the _inittab struct.
if line.startswith("struct _inittab"):
log("adding %s declaration to config.c" % init_fn)
lines.append("extern PyObject* %s(void);" % init_fn)
# Insert the extension in the _inittab struct.
if line.lstrip().startswith("/* Sentinel */"):
log("marking %s as a built-in extension module" % extension)
lines.append('{"%s", %s},' % (extension, init_fn))
lines.append(line)
with config_c_path.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
def remove_from_extension_modules(source_path: pathlib.Path, extension: str):
"""Remove an extension from the set of extension/external modules.
Call this when an extension will be compiled into libpython instead of
compiled as a standalone extension.
"""
RE_EXTENSION_MODULES = re.compile('<(Extension|External)Modules Include="([^"]+)"')
pcbuild_proj_path = source_path / "PCbuild" / "pcbuild.proj"
lines = []
with pcbuild_proj_path.open("r", encoding="utf8") as fh:
for line in fh:
line = line.rstrip()
m = RE_EXTENSION_MODULES.search(line)
if m:
modules = [m for m in m.group(2).split(";") if m != extension]
# Ignore line if new value is empty.
if not modules:
continue
line = line.replace(m.group(2), ";".join(modules))
lines.append(line)
with pcbuild_proj_path.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
def make_project_static_library(source_path: pathlib.Path, project: str):
"""Turn a project file into a static library."""
proj_path = source_path / "PCbuild" / ("%s.vcxproj" % project)
lines = []
found_config_type = False
found_target_ext = False
with proj_path.open("r", encoding="utf8") as fh:
for line in fh:
line = line.rstrip()
# Change the project configuration to a static library.
if "<ConfigurationType>DynamicLibrary</ConfigurationType>" in line:
log("changing %s to a static library" % project)
found_config_type = True
line = line.replace("DynamicLibrary", "StaticLibrary")
elif "<ConfigurationType>StaticLibrary</ConfigurationType>" in line:
log("%s is already a static library" % project)
return
# Change the output file name from .pyd to .lib because it is no
# longer an extension.
if "<TargetExt>.pyd</TargetExt>" in line:
log("changing output of %s to a .lib" % project)
found_target_ext = True
line = line.replace(".pyd", ".lib")
lines.append(line)
if not found_config_type:
log("failed to adjust config type for %s" % project)
sys.exit(1)
if not found_target_ext:
log("failed to adjust target extension for %s" % project)
sys.exit(1)
with proj_path.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
def convert_to_static_library(
source_path: pathlib.Path,
extension: str,
entry: dict,
honor_allow_missing_preprocessor: bool,
):
"""Converts an extension to a static library."""
proj_path = source_path / "PCbuild" / ("%s.vcxproj" % extension)
if not proj_path.exists() and entry.get("ignore_missing"):
return False
# Make the extension's project emit a static library so we can link
# against libpython.
make_project_static_library(source_path, extension)
# And do the same thing for its dependencies.
for project in entry.get("static_depends", []):
make_project_static_library(source_path, project)
copy_link_to_lib(proj_path)
lines = []
RE_PREPROCESSOR_DEFINITIONS = re.compile(
"<PreprocessorDefinitions[^>]*>([^<]+)</PreprocessorDefinitions>"
)
found_preprocessor = False
itemgroup_line = None
itemdefinitiongroup_line = None
with proj_path.open("r", encoding="utf8") as fh:
for i, line in enumerate(fh):
line = line.rstrip()
# Add Py_BUILD_CORE_BUILTIN to preprocessor definitions so linkage
# data is correct.
m = RE_PREPROCESSOR_DEFINITIONS.search(line)
# But don't do it if it is an annotation for an individual source file.
if m and "<ClCompile Include=" not in lines[i - 1]:
log("adding Py_BUILD_CORE_BUILTIN to %s" % extension)
found_preprocessor = True
line = line.replace(m.group(1), "Py_BUILD_CORE_BUILTIN;%s" % m.group(1))
# Find the first <ItemGroup> entry.
if "<ItemGroup>" in line and not itemgroup_line:
itemgroup_line = i
# Find the first <ItemDefinitionGroup> entry.
if "<ItemDefinitionGroup>" in line and not itemdefinitiongroup_line:
itemdefinitiongroup_line = i
lines.append(line)
if not found_preprocessor:
if honor_allow_missing_preprocessor and entry.get("allow_missing_preprocessor"):
log("not adjusting preprocessor definitions for %s" % extension)
else:
log("introducing <PreprocessorDefinitions> to %s" % extension)
lines[itemgroup_line:itemgroup_line] = [
" <ItemDefinitionGroup>",
" <ClCompile>",
" <PreprocessorDefinitions>Py_BUILD_CORE_BUILTIN;%(PreprocessorDefinitions)</PreprocessorDefinitions>",
" </ClCompile>",
" </ItemDefinitionGroup>",
]
itemdefinitiongroup_line = itemgroup_line + 1
if "static_depends" in entry:
if not itemdefinitiongroup_line:
log("unable to find <ItemDefinitionGroup> for %s" % extension)
sys.exit(1)
log("changing %s to automatically link library dependencies" % extension)
lines[itemdefinitiongroup_line + 1 : itemdefinitiongroup_line + 1] = [
" <ProjectReference>",
" <LinkLibraryDependencies>true</LinkLibraryDependencies>",
" </ProjectReference>",
]
# Ensure the extension project doesn't depend on pythoncore: as a built-in
# extension, pythoncore will depend on it.
# This logic is a bit hacky. Ideally we'd parse the file as XML and operate
# in the XML domain. But that is more work. The goal here is to strip the
# <ProjectReference>...</ProjectReference> containing the
# <Project>{pythoncore ID}</Project>. This could leave an item <ItemGroup>.
# That should be fine.
start_line, end_line = None, None
for i, line in enumerate(lines):
if "<Project>{cf7ac3d1-e2df-41d2-bea6-1e2556cdea26}</Project>" in line:
for j in range(i, 0, -1):
if "<ProjectReference" in lines[j]:
start_line = j
break
for j in range(i, len(lines) - 1):
if "</ProjectReference>" in lines[j]:
end_line = j
break
break
if start_line is not None and end_line is not None:
log("stripping pythoncore dependency from %s" % extension)
for line in lines[start_line : end_line + 1]:
log(line)
lines = lines[:start_line] + lines[end_line + 1 :]
with proj_path.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
# Tell pythoncore to link against the static .lib.
RE_ADDITIONAL_DEPENDENCIES = re.compile(
"<AdditionalDependencies>([^<]+)</AdditionalDependencies>"
)
pythoncore_path = source_path / "PCbuild" / "pythoncore.vcxproj"
lines = []
with pythoncore_path.open("r", encoding="utf8") as fh:
for line in fh:
line = line.rstrip()
m = RE_ADDITIONAL_DEPENDENCIES.search(line)
if m:
log("changing pythoncore to link against %s.lib" % extension)
# TODO we shouldn't need this with static linking if the
# project is configured to link library dependencies.
# But removing it results in unresolved external symbols
# when linking the python project. There /might/ be a
# visibility issue with the PyMODINIT_FUNC macro.
line = line.replace(
m.group(1), r"$(OutDir)%s.lib;%s" % (extension, m.group(1))
)
lines.append(line)
with pythoncore_path.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
# Change pythoncore to depend on the extension project.
# pcbuild.proj is the file that matters for msbuild. And order within
# matters. We remove the extension from the "ExtensionModules" set of
# projects. Then we re-add the project to before "pythoncore."
remove_from_extension_modules(source_path, extension)
pcbuild_proj_path = source_path / "PCbuild" / "pcbuild.proj"
with pcbuild_proj_path.open("r", encoding="utf8") as fh:
data = fh.read()
data = data.replace(
'<Projects Include="pythoncore.vcxproj">',
' <Projects Include="%s.vcxproj" />\n <Projects Include="pythoncore.vcxproj">'
% extension,
)
with pcbuild_proj_path.open("w", encoding="utf8") as fh:
fh.write(data)
# We don't technically need to modify the solution since msbuild doesn't
# use it. But it enables debugging inside Visual Studio, which is
# convenient.
RE_PROJECT = re.compile(
'Project\("\{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942\}"\) = "([^"]+)", "[^"]+", "{([^\}]+)\}"'
)
pcbuild_sln_path = source_path / "PCbuild" / "pcbuild.sln"
lines = []
extension_id = None
pythoncore_line = None
with pcbuild_sln_path.open("r", encoding="utf8") as fh:
# First pass buffers the file, finds the ID of the extension project,
# and finds where the pythoncore project is defined.
for i, line in enumerate(fh):
line = line.rstrip()
m = RE_PROJECT.search(line)
if m and m.group(1) == extension:
extension_id = m.group(2)
if m and m.group(1) == "pythoncore":
pythoncore_line = i
lines.append(line)
# Not all projects are in the solution(!!!). Since we don't use the
# solution for building, that's fine to ignore.
if not extension_id:
log("failed to find project %s in solution" % extension)
if not pythoncore_line:
log("failed to find pythoncore project in solution")
if extension_id and pythoncore_line:
log("making pythoncore depend on %s" % extension)
needs_section = (
not lines[pythoncore_line + 1].lstrip().startswith("ProjectSection")
)
offset = 1 if needs_section else 2
lines.insert(
pythoncore_line + offset, "\t\t{%s} = {%s}" % (extension_id, extension_id)
)
if needs_section:
lines.insert(
pythoncore_line + 1,
"\tProjectSection(ProjectDependencies) = postProject",
)
lines.insert(pythoncore_line + 3, "\tEndProjectSection")
with pcbuild_sln_path.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
return True
def copy_link_to_lib(p: pathlib.Path):
"""Copy the contents of a <Link> section to a <Lib> section."""
lines = []
copy_lines = []
copy_active = False
with p.open("r", encoding="utf8") as fh:
for line in fh:
line = line.rstrip()
lines.append(line)
if "<Link>" in line:
copy_active = True
continue
elif "</Link>" in line:
copy_active = False
log("duplicating <Link> section in %s" % p)
lines.append(" <Lib>")
lines.extend(copy_lines)
lines.append(" </Lib>")
if copy_active:
copy_lines.append(line)
with p.open("w", encoding="utf8") as fh:
fh.write("\n".join(lines))
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)')" AfterTargets="Build">
<Copy SourceFiles="@(_SSLDLL)" DestinationFolder="$(OutDir)" />
</Target>
<Target Name="_CleanSSLDLL" 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, static: bool,
):
# 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"]
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)
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()
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
lines.append(line)
with python_props_path.open("wb") as fh:
fh.write(b"\n".join(lines))
tcltkprops_path = pcbuild_path / "tcltk.props"
static_replace_in_file(
tcltkprops_path,
br"<tcltkDir>$(ExternalsDir)tcltk-$(TclMajorVersion).$(TclMinorVersion).$(TclPatchLevel).$(TclRevision)\$(ArchName)\</tcltkDir>",
br"<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 static:
# We don't need the install rules to copy the libcrypto and libssl DLLs.
static_replace_in_file(
openssl_props,
OPENSSL_PROPS_REMOVE_RULES.strip().replace(b"\n", b"\r\n"),
b"",
)
# We need to copy linking settings for dynamic libraries to static libraries.
copy_link_to_lib(pcbuild_path / "libffi.props")
copy_link_to_lib(pcbuild_path / "openssl.props")
# We should look against the static library variants.
static_replace_in_file(
openssl_props,
b"libcrypto.lib;libssl.lib;",
b"libcrypto_static.lib;libssl_static.lib;",
)
else:
if arch == "amd64":
suffix = b"x64"
elif arch == "win32":
suffix = None
elif arch == "arm64":
suffix = b"arm64" # TODO check it
else:
raise Exception("unhandled architecture: %s" % arch)
if suffix:
static_replace_in_file(
openssl_props,
b"<_DLLSuffix>-1_1</_DLLSuffix>",
b"<_DLLSuffix>-1_1-%s</_DLLSuffix>" % suffix,
)
libffi_props = pcbuild_path / "libffi.props"
if static:
# For some reason the built .lib doesn't have the -7 suffix in
# static build mode. This is possibly a side-effect of CPython's
# libffi build script not officially supporting static-only builds.
static_replace_in_file(
libffi_props,
b"<AdditionalDependencies>libffi-7.lib;%(AdditionalDependencies)</AdditionalDependencies>",
b"<AdditionalDependencies>libffi.lib;%(AdditionalDependencies)</AdditionalDependencies>",
)
static_replace_in_file(
libffi_props, LIBFFI_PROPS_REMOVE_RULES.strip().replace(b"\n", b"\r\n"), b""
)
def hack_project_files(
td: pathlib.Path,
cpython_source_path: pathlib.Path,
build_directory: str,
static: bool,
honor_allow_missing_preprocessor: bool,
):
"""Hacks Visual Studio project files to work with our build."""
pcbuild_path = cpython_source_path / "PCbuild"
hack_props(
td, pcbuild_path, build_directory, static=static,
)
# 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,
br"<_SqliteVersion>$([System.Text.RegularExpressions.Regex]::Match(`$(sqlite3Dir)`, `((\d+)\.(\d+)\.(\d+)\.(\d+))\\?$`).Groups)</_SqliteVersion>",
br"<_SqliteVersion>%s</_SqliteVersion>" % sqlite3_version,
)
static_replace_in_file(
sqlite3_path,
br"<SqliteVersion>$(_SqliteVersion.Split(`;`)[1])</SqliteVersion>",
br"<SqliteVersion>%s</SqliteVersion>" % sqlite3_version,
)
static_replace_in_file(
sqlite3_path,
br"<SqliteMajorVersion>$(_SqliteVersion.Split(`;`)[2])</SqliteMajorVersion>",
br"<SqliteMajorVersion>%s</SqliteMajorVersion>" % sqlite3_version_parts[0],
)
static_replace_in_file(
sqlite3_path,
br"<SqliteMinorVersion>$(_SqliteVersion.Split(`;`)[3])</SqliteMinorVersion>",
br"<SqliteMinorVersion>%s</SqliteMinorVersion>" % sqlite3_version_parts[1],
)
static_replace_in_file(
sqlite3_path,
br"<SqliteMicroVersion>$(_SqliteVersion.Split(`;`)[4])</SqliteMicroVersion>",
br"<SqliteMicroVersion>%s</SqliteMicroVersion>" % sqlite3_version_parts[2],
)
static_replace_in_file(
sqlite3_path,
br"<SqlitePatchVersion>$(_SqliteVersion.Split(`;`)[5])</SqlitePatchVersion>",
br"<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.
liblzma_path = pcbuild_path / "liblzma.vcxproj"
static_replace_in_file(
liblzma_path,
br"$(lzmaDir)windows;$(lzmaDir)src/liblzma/common;",
br"$(lzmaDir)windows\vs2017;$(lzmaDir)src/liblzma/common;",
)
static_replace_in_file(
liblzma_path,
br'<ClInclude Include="$(lzmaDir)windows\config.h" />',
br'<ClInclude Include="$(lzmaDir)windows\vs2017\config.h" />',
)
# 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",
br"<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,
br'<ClCompile Include="$(opensslIncludeDir)\applink.c">',
br'<ClCompile Include="$(opensslIncludeDir)\openssl\applink.c">',
)
pythoncore_proj = pcbuild_path / "pythoncore.vcxproj"
if static:
for extension, entry in sorted(CONVERT_TO_BUILTIN_EXTENSIONS.items()):
if entry.get("ignore_static"):
log("ignoring extension %s in static builds" % extension)
continue
init_fn = entry.get("init", "PyInit_%s" % extension)
if convert_to_static_library(
cpython_source_path, extension, entry, honor_allow_missing_preprocessor
):
add_to_config_c(cpython_source_path, extension, init_fn)
# pythoncore.vcxproj produces libpython. Typically pythonXY.dll. We change
# it to produce a static library.
pyproject_props = pcbuild_path / "pyproject.props"
# Need to replace Py_ENABLE_SHARED with Py_NO_ENABLE_SHARED so symbol
# visibility is proper.
# Replacing it in the global properties file has the most bang for our buck.
if static:
static_replace_in_file(
pyproject_props,
b"<PreprocessorDefinitions>WIN32;",
b"<PreprocessorDefinitions>Py_NO_ENABLE_SHARED;WIN32;",
)
static_replace_in_file(
pythoncore_proj, b"Py_ENABLE_SHARED", b"Py_NO_ENABLE_SHARED"
)
# Disable whole program optimization because it interferes with the format
# of object files and makes it so we can't easily consume their symbols.
# TODO this /might/ be OK once we figure out symbol exporting issues.
if static:
static_replace_in_file(
pyproject_props,
b"<WholeProgramOptimization>true</WholeProgramOptimization>",
b"<WholeProgramOptimization>false</WholeProgramOptimization>",
)
# Make libpython a static library.
if static:
static_replace_in_file(
pythoncore_proj,
b"<ConfigurationType>DynamicLibrary</ConfigurationType>",
b"<ConfigurationType>StaticLibrary</ConfigurationType>",
)
copy_link_to_lib(pythoncore_proj)
# 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"",
)
if static:
static_replace_in_file(
pcbuild_proj, b'<Projects Include="python3dll.vcxproj" />', 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).
static_replace_in_file(
pcbuild_proj,
b"""<Projects2 Condition="$(Platform) != 'ARM' and $(Platform) != 'ARM64'" Include="_freeze_importlib.vcxproj" />""",
b"",
)
# Switch to the static version of the run-time library.