-
-
Notifications
You must be signed in to change notification settings - Fork 30.3k
/
build-installer.py
executable file
·1778 lines (1532 loc) · 64.2 KB
/
build-installer.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 python
"""
This script is used to build "official" universal installers on macOS.
NEW for 3.10 and backports:
- support universal2 variant with arm64 and x86_64 archs
- enable clang optimizations when building on 10.15+
NEW for 3.9.0 and backports:
- 2.7 end-of-life issues:
- Python 3 installs now update the Current version link
in /Library/Frameworks/Python.framework/Versions
- fully support running under Python 3 as well as 2.7
- support building on newer macOS systems with SIP
- fully support building on macOS 10.9+
- support 10.6+ on best effort
- support bypassing docs build by supplying a prebuilt
docs html tarball in the third-party source library,
in the format and filename conventional of those
downloadable from python.org:
python-3.x.y-docs-html.tar.bz2
NEW for 3.7.0:
- support Intel 64-bit-only () and 32-bit-only installer builds
- build and use internal Tcl/Tk 8.6 for 10.6+ builds
- deprecate use of explicit SDK (--sdk-path=) since all but the oldest
versions of Xcode support implicit setting of an SDK via environment
variables (SDKROOT and friends, see the xcrun man page for more info).
The SDK stuff was primarily needed for building universal installers
for 10.4; so as of 3.7.0, building installers for 10.4 is no longer
supported with build-installer.
- use generic "gcc" as compiler (CC env var) rather than "gcc-4.2"
TODO:
- test building with SDKROOT and DEVELOPER_DIR xcrun env variables
Usage: see USAGE variable in the script.
"""
import platform, os, sys, getopt, textwrap, shutil, stat, time, pwd, grp
try:
import urllib2 as urllib_request
except ImportError:
import urllib.request as urllib_request
STAT_0o755 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
| stat.S_IRGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH )
STAT_0o775 = ( stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
| stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP
| stat.S_IROTH | stat.S_IXOTH )
INCLUDE_TIMESTAMP = 1
VERBOSE = 1
RUNNING_ON_PYTHON2 = sys.version_info.major == 2
if RUNNING_ON_PYTHON2:
from plistlib import writePlist
else:
from plistlib import dump
def writePlist(path, plist):
with open(plist, 'wb') as fp:
dump(path, fp)
def shellQuote(value):
"""
Return the string value in a form that can safely be inserted into
a shell command.
"""
return "'%s'"%(value.replace("'", "'\"'\"'"))
def grepValue(fn, variable):
"""
Return the unquoted value of a variable from a file..
QUOTED_VALUE='quotes' -> str('quotes')
UNQUOTED_VALUE=noquotes -> str('noquotes')
"""
variable = variable + '='
for ln in open(fn, 'r'):
if ln.startswith(variable):
value = ln[len(variable):].strip()
return value.strip("\"'")
raise RuntimeError("Cannot find variable %s" % variable[:-1])
_cache_getVersion = None
def getVersion():
global _cache_getVersion
if _cache_getVersion is None:
_cache_getVersion = grepValue(
os.path.join(SRCDIR, 'configure'), 'PACKAGE_VERSION')
return _cache_getVersion
def getVersionMajorMinor():
return tuple([int(n) for n in getVersion().split('.', 2)])
_cache_getFullVersion = None
def getFullVersion():
global _cache_getFullVersion
if _cache_getFullVersion is not None:
return _cache_getFullVersion
fn = os.path.join(SRCDIR, 'Include', 'patchlevel.h')
for ln in open(fn):
if 'PY_VERSION' in ln:
_cache_getFullVersion = ln.split()[-1][1:-1]
return _cache_getFullVersion
raise RuntimeError("Cannot find full version??")
FW_PREFIX = ["Library", "Frameworks", "Python.framework"]
FW_VERSION_PREFIX = "--undefined--" # initialized in parseOptions
FW_SSL_DIRECTORY = "--undefined--" # initialized in parseOptions
# The directory we'll use to create the build (will be erased and recreated)
WORKDIR = "/tmp/_py"
# The directory we'll use to store third-party sources. Set this to something
# else if you don't want to re-fetch required libraries every time.
DEPSRC = os.path.join(WORKDIR, 'third-party')
DEPSRC = os.path.expanduser('~/Universal/other-sources')
universal_opts_map = { 'universal2': ('arm64', 'x86_64'),
'32-bit': ('i386', 'ppc',),
'64-bit': ('x86_64', 'ppc64',),
'intel': ('i386', 'x86_64'),
'intel-32': ('i386',),
'intel-64': ('x86_64',),
'3-way': ('ppc', 'i386', 'x86_64'),
'all': ('i386', 'ppc', 'x86_64', 'ppc64',) }
default_target_map = {
'universal2': '10.9',
'64-bit': '10.5',
'3-way': '10.5',
'intel': '10.5',
'intel-32': '10.4',
'intel-64': '10.5',
'all': '10.5',
}
UNIVERSALOPTS = tuple(universal_opts_map.keys())
UNIVERSALARCHS = '32-bit'
ARCHLIST = universal_opts_map[UNIVERSALARCHS]
# Source directory (assume we're in Mac/BuildScript)
SRCDIR = os.path.dirname(
os.path.dirname(
os.path.dirname(
os.path.abspath(__file__
))))
# $MACOSX_DEPLOYMENT_TARGET -> minimum OS X level
DEPTARGET = '10.5'
def getDeptargetTuple():
return tuple([int(n) for n in DEPTARGET.split('.')[0:2]])
def getBuildTuple():
return tuple([int(n) for n in platform.mac_ver()[0].split('.')[0:2]])
def getTargetCompilers():
target_cc_map = {
'10.4': ('gcc-4.0', 'g++-4.0'),
'10.5': ('gcc', 'g++'),
'10.6': ('gcc', 'g++'),
'10.7': ('gcc', 'g++'),
'10.8': ('gcc', 'g++'),
}
return target_cc_map.get(DEPTARGET, ('clang', 'clang++') )
CC, CXX = getTargetCompilers()
PYTHON_3 = getVersionMajorMinor() >= (3, 0)
USAGE = textwrap.dedent("""\
Usage: build_python [options]
Options:
-? or -h: Show this message
-b DIR
--build-dir=DIR: Create build here (default: %(WORKDIR)r)
--third-party=DIR: Store third-party sources here (default: %(DEPSRC)r)
--sdk-path=DIR: Location of the SDK (deprecated, use SDKROOT env variable)
--src-dir=DIR: Location of the Python sources (default: %(SRCDIR)r)
--dep-target=10.n macOS deployment target (default: %(DEPTARGET)r)
--universal-archs=x universal architectures (options: %(UNIVERSALOPTS)r, default: %(UNIVERSALARCHS)r)
""")% globals()
# Dict of object file names with shared library names to check after building.
# This is to ensure that we ended up dynamically linking with the shared
# library paths and versions we expected. For example:
# EXPECTED_SHARED_LIBS['_tkinter.so'] = [
# '/Library/Frameworks/Tcl.framework/Versions/8.5/Tcl',
# '/Library/Frameworks/Tk.framework/Versions/8.5/Tk']
EXPECTED_SHARED_LIBS = {}
# Are we building and linking with our own copy of Tcl/TK?
# For now, do so if deployment target is 10.6+.
def internalTk():
return getDeptargetTuple() >= (10, 6)
# Do we use 8.6.8 when building our own copy
# of Tcl/Tk or a modern version.
# We use the old version when building on
# old versions of macOS due to build issues.
def useOldTk():
return getBuildTuple() < (10, 15)
def tweak_tcl_build(basedir, archList):
with open("Makefile", "r") as fp:
contents = fp.readlines()
# For reasons I don't understand the tcl configure script
# decides that some stdlib symbols aren't present, before
# deciding that strtod is broken.
new_contents = []
for line in contents:
if line.startswith("COMPAT_OBJS"):
# note: the space before strtod.o is intentional,
# the detection of a broken strtod results in
# "fixstrod.o" on this line.
for nm in ("strstr.o", "strtoul.o", " strtod.o"):
line = line.replace(nm, "")
new_contents.append(line)
with open("Makefile", "w") as fp:
fp.writelines(new_contents)
# List of names of third party software built with this installer.
# The names will be inserted into the rtf version of the License.
THIRD_PARTY_LIBS = []
# Instructions for building libraries that are necessary for building a
# batteries included python.
# [The recipes are defined here for convenience but instantiated later after
# command line options have been processed.]
def library_recipes():
result = []
# Since Apple removed the header files for the deprecated system
# OpenSSL as of the Xcode 7 release (for OS X 10.10+), we do not
# have much choice but to build our own copy here, too.
result.extend([
dict(
name="OpenSSL 3.0.15",
url="https://github.com/openssl/openssl/releases/download/openssl-3.0.15/openssl-3.0.15.tar.gz",
checksum='23c666d0edf20f14249b3d8f0368acaee9ab585b09e1de82107c66e1f3ec9533',
buildrecipe=build_universal_openssl,
configure=None,
install=None,
),
])
if internalTk():
if useOldTk():
tcl_tk_ver='8.6.8'
tcl_checksum='81656d3367af032e0ae6157eff134f89'
tk_checksum='5e0faecba458ee1386078fb228d008ba'
tk_patches = ['backport_gh71383_fix.patch', 'tk868_on_10_8_10_9.patch', 'backport_gh110950_fix.patch']
else:
tcl_tk_ver='8.6.15'
tcl_checksum='861e159753f2e2fbd6ec1484103715b0be56be3357522b858d3cbb5f893ffef1'
tk_checksum='550969f35379f952b3020f3ab7b9dd5bfd11c1ef7c9b7c6a75f5c49aca793fec'
tk_patches = []
base_url = "https://prdownloads.sourceforge.net/tcl/{what}{version}-src.tar.gz"
result.extend([
dict(
name="Tcl %s"%(tcl_tk_ver,),
url=base_url.format(what="tcl", version=tcl_tk_ver),
checksum=tcl_checksum,
buildDir="unix",
configure_pre=[
'--enable-shared',
'--enable-threads',
'--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib'%(getVersion(),),
],
useLDFlags=False,
buildrecipe=tweak_tcl_build,
install='make TCL_LIBRARY=%(TCL_LIBRARY)s && make install TCL_LIBRARY=%(TCL_LIBRARY)s DESTDIR=%(DESTDIR)s'%{
"DESTDIR": shellQuote(os.path.join(WORKDIR, 'libraries')),
"TCL_LIBRARY": shellQuote('/Library/Frameworks/Python.framework/Versions/%s/lib/tcl8.6'%(getVersion())),
},
),
dict(
name="Tk %s"%(tcl_tk_ver,),
url=base_url.format(what="tk", version=tcl_tk_ver),
checksum=tk_checksum,
patches=tk_patches,
buildDir="unix",
configure_pre=[
'--enable-aqua',
'--enable-shared',
'--enable-threads',
'--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib'%(getVersion(),),
],
useLDFlags=False,
install='make TCL_LIBRARY=%(TCL_LIBRARY)s TK_LIBRARY=%(TK_LIBRARY)s && make install TCL_LIBRARY=%(TCL_LIBRARY)s TK_LIBRARY=%(TK_LIBRARY)s DESTDIR=%(DESTDIR)s'%{
"DESTDIR": shellQuote(os.path.join(WORKDIR, 'libraries')),
"TCL_LIBRARY": shellQuote('/Library/Frameworks/Python.framework/Versions/%s/lib/tcl8.6'%(getVersion())),
"TK_LIBRARY": shellQuote('/Library/Frameworks/Python.framework/Versions/%s/lib/tk8.6'%(getVersion())),
},
),
])
if PYTHON_3:
result.extend([
dict(
name="XZ 5.2.3",
url="http://tukaani.org/xz/xz-5.2.3.tar.gz",
checksum='ef68674fb47a8b8e741b34e429d86e9d',
configure_pre=[
'--disable-dependency-tracking',
]
),
])
result.extend([
dict(
name="NCurses 5.9",
url="http://ftp.gnu.org/pub/gnu/ncurses/ncurses-5.9.tar.gz",
checksum='8cb9c412e5f2d96bc6f459aa8c6282a1',
configure_pre=[
"--enable-widec",
"--without-cxx",
"--without-cxx-binding",
"--without-ada",
"--without-curses-h",
"--enable-shared",
"--with-shared",
"--without-debug",
"--without-normal",
"--without-tests",
"--without-manpages",
"--datadir=/usr/share",
"--sysconfdir=/etc",
"--sharedstatedir=/usr/com",
"--with-terminfo-dirs=/usr/share/terminfo",
"--with-default-terminfo-dir=/usr/share/terminfo",
"--libdir=/Library/Frameworks/Python.framework/Versions/%s/lib"%(getVersion(),),
],
patchscripts=[
("ftp://ftp.invisible-island.net/ncurses//5.9/ncurses-5.9-20120616-patch.sh.bz2",
"f54bf02a349f96a7c4f0d00922f3a0d4"),
],
useLDFlags=False,
install='make && make install DESTDIR=%s && cd %s/usr/local/lib && ln -fs ../../../Library/Frameworks/Python.framework/Versions/%s/lib/lib* .'%(
shellQuote(os.path.join(WORKDIR, 'libraries')),
shellQuote(os.path.join(WORKDIR, 'libraries')),
getVersion(),
),
),
dict(
name="SQLite 3.45.3",
url="https://sqlite.org/2024/sqlite-autoconf-3450300.tar.gz",
checksum="b2809ca53124c19c60f42bf627736eae011afdcc205bb48270a5ee9a38191531",
extra_cflags=('-Os '
'-DSQLITE_ENABLE_FTS5 '
'-DSQLITE_ENABLE_FTS4 '
'-DSQLITE_ENABLE_FTS3_PARENTHESIS '
'-DSQLITE_ENABLE_RTREE '
'-DSQLITE_OMIT_AUTOINIT '
'-DSQLITE_TCL=0 '
),
configure_pre=[
'--enable-threadsafe',
'--enable-shared=no',
'--enable-static=yes',
'--disable-readline',
'--disable-dependency-tracking',
]
),
dict(
name="libmpdec 4.0.0",
url="https://www.bytereef.org/software/mpdecimal/releases/mpdecimal-4.0.0.tar.gz",
checksum="942445c3245b22730fd41a67a7c5c231d11cb1b9936b9c0f76334fb7d0b4468c",
configure_pre=[
"--disable-cxx",
"MACHINE=universal",
]
),
])
if not PYTHON_3:
result.extend([
dict(
name="Sleepycat DB 4.7.25",
url="http://download.oracle.com/berkeley-db/db-4.7.25.tar.gz",
checksum='ec2b87e833779681a0c3a814aa71359e',
buildDir="build_unix",
configure="../dist/configure",
configure_pre=[
'--includedir=/usr/local/include/db4',
]
),
])
return result
def compilerCanOptimize():
"""
Return True iff the default Xcode version can use PGO and LTO
"""
# bpo-42235: The version check is pretty conservative, can be
# adjusted after testing
mac_ver = tuple(map(int, platform.mac_ver()[0].split('.')))
return mac_ver >= (10, 15)
# Instructions for building packages inside the .mpkg.
def pkg_recipes():
unselected_for_python3 = ('selected', 'unselected')[PYTHON_3]
result = [
dict(
name="PythonFramework",
long_name="Python Framework",
source="/Library/Frameworks/Python.framework",
readme="""\
This package installs Python.framework, that is the python
interpreter and the standard library.
""",
postflight="scripts/postflight.framework",
selected='selected',
),
dict(
name="PythonApplications",
long_name="GUI Applications",
source="/Applications/Python %(VER)s",
readme="""\
This package installs IDLE (an interactive Python IDE),
Python Launcher and Build Applet (create application bundles
from python scripts).
It also installs a number of examples and demos.
""",
required=False,
selected='selected',
),
dict(
name="PythonUnixTools",
long_name="UNIX command-line tools",
source="/usr/local/bin",
readme="""\
This package installs the unix tools in /usr/local/bin for
compatibility with older releases of Python. This package
is not necessary to use Python.
""",
required=False,
selected='selected',
),
dict(
name="PythonDocumentation",
long_name="Python Documentation",
topdir="/Library/Frameworks/Python.framework/Versions/%(VER)s/Resources/English.lproj/Documentation",
source="/pydocs",
readme="""\
This package installs the python documentation at a location
that is usable for pydoc and IDLE.
""",
postflight="scripts/postflight.documentation",
required=False,
selected='selected',
),
dict(
name="PythonProfileChanges",
long_name="Shell profile updater",
readme="""\
This packages updates your shell profile to make sure that
the Python tools are found by your shell in preference of
the system provided Python tools.
If you don't install this package you'll have to add
"/Library/Frameworks/Python.framework/Versions/%(VER)s/bin"
to your PATH by hand.
""",
postflight="scripts/postflight.patch-profile",
topdir="/Library/Frameworks/Python.framework",
source="/empty-dir",
required=False,
selected='selected',
),
dict(
name="PythonInstallPip",
long_name="Install or upgrade pip",
readme="""\
This package installs (or upgrades from an earlier version)
pip, a tool for installing and managing Python packages.
""",
postflight="scripts/postflight.ensurepip",
topdir="/Library/Frameworks/Python.framework",
source="/empty-dir",
required=False,
selected='selected',
),
]
return result
def fatal(msg):
"""
A fatal error, bail out.
"""
sys.stderr.write('FATAL: ')
sys.stderr.write(msg)
sys.stderr.write('\n')
sys.exit(1)
def fileContents(fn):
"""
Return the contents of the named file
"""
return open(fn, 'r').read()
def runCommand(commandline):
"""
Run a command and raise RuntimeError if it fails. Output is suppressed
unless the command fails.
"""
fd = os.popen(commandline, 'r')
data = fd.read()
xit = fd.close()
if xit is not None:
sys.stdout.write(data)
raise RuntimeError("command failed: %s"%(commandline,))
if VERBOSE:
sys.stdout.write(data); sys.stdout.flush()
def captureCommand(commandline):
fd = os.popen(commandline, 'r')
data = fd.read()
xit = fd.close()
if xit is not None:
sys.stdout.write(data)
raise RuntimeError("command failed: %s"%(commandline,))
return data
def getTclTkVersion(configfile, versionline):
"""
search Tcl or Tk configuration file for version line
"""
try:
f = open(configfile, "r")
except OSError:
fatal("Framework configuration file not found: %s" % configfile)
for l in f:
if l.startswith(versionline):
f.close()
return l
fatal("Version variable %s not found in framework configuration file: %s"
% (versionline, configfile))
def checkEnvironment():
"""
Check that we're running on a supported system.
"""
if sys.version_info[0:2] < (2, 7):
fatal("This script must be run with Python 2.7 (or later)")
if platform.system() != 'Darwin':
fatal("This script should be run on a macOS 10.5 (or later) system")
if int(platform.release().split('.')[0]) < 8:
fatal("This script should be run on a macOS 10.5 (or later) system")
# Because we only support dynamic load of only one major/minor version of
# Tcl/Tk, if we are not using building and using our own private copy of
# Tcl/Tk, ensure:
# 1. there is a user-installed framework (usually ActiveTcl) in (or linked
# in) SDKROOT/Library/Frameworks. As of Python 3.7.0, we no longer
# enforce that the version of the user-installed framework also
# exists in the system-supplied Tcl/Tk frameworks. Time to support
# Tcl/Tk 8.6 even if Apple does not.
if not internalTk():
frameworks = {}
for framework in ['Tcl', 'Tk']:
fwpth = 'Library/Frameworks/%s.framework/Versions/Current' % framework
libfw = os.path.join('/', fwpth)
usrfw = os.path.join(os.getenv('HOME'), fwpth)
frameworks[framework] = os.readlink(libfw)
if not os.path.exists(libfw):
fatal("Please install a link to a current %s %s as %s so "
"the user can override the system framework."
% (framework, frameworks[framework], libfw))
if os.path.exists(usrfw):
fatal("Please rename %s to avoid possible dynamic load issues."
% usrfw)
if frameworks['Tcl'] != frameworks['Tk']:
fatal("The Tcl and Tk frameworks are not the same version.")
print(" -- Building with external Tcl/Tk %s frameworks"
% frameworks['Tk'])
# add files to check after build
EXPECTED_SHARED_LIBS['_tkinter.so'] = [
"/Library/Frameworks/Tcl.framework/Versions/%s/Tcl"
% frameworks['Tcl'],
"/Library/Frameworks/Tk.framework/Versions/%s/Tk"
% frameworks['Tk'],
]
else:
print(" -- Building private copy of Tcl/Tk")
print("")
# Remove inherited environment variables which might influence build
environ_var_prefixes = ['CPATH', 'C_INCLUDE_', 'DYLD_', 'LANG', 'LC_',
'LD_', 'LIBRARY_', 'PATH', 'PYTHON']
for ev in list(os.environ):
for prefix in environ_var_prefixes:
if ev.startswith(prefix) :
print("INFO: deleting environment variable %s=%s" % (
ev, os.environ[ev]))
del os.environ[ev]
base_path = '/bin:/sbin:/usr/bin:/usr/sbin'
if 'SDK_TOOLS_BIN' in os.environ:
base_path = os.environ['SDK_TOOLS_BIN'] + ':' + base_path
# Xcode 2.5 on OS X 10.4 does not include SetFile in its usr/bin;
# add its fixed location here if it exists
OLD_DEVELOPER_TOOLS = '/Developer/Tools'
if os.path.isdir(OLD_DEVELOPER_TOOLS):
base_path = base_path + ':' + OLD_DEVELOPER_TOOLS
os.environ['PATH'] = base_path
print("Setting default PATH: %s"%(os.environ['PATH']))
def parseOptions(args=None):
"""
Parse arguments and update global settings.
"""
global WORKDIR, DEPSRC, SRCDIR, DEPTARGET
global UNIVERSALOPTS, UNIVERSALARCHS, ARCHLIST, CC, CXX
global FW_VERSION_PREFIX
global FW_SSL_DIRECTORY
if args is None:
args = sys.argv[1:]
try:
options, args = getopt.getopt(args, '?hb',
[ 'build-dir=', 'third-party=', 'sdk-path=' , 'src-dir=',
'dep-target=', 'universal-archs=', 'help' ])
except getopt.GetoptError:
print(sys.exc_info()[1])
sys.exit(1)
if args:
print("Additional arguments")
sys.exit(1)
deptarget = None
for k, v in options:
if k in ('-h', '-?', '--help'):
print(USAGE)
sys.exit(0)
elif k in ('-d', '--build-dir'):
WORKDIR=v
elif k in ('--third-party',):
DEPSRC=v
elif k in ('--sdk-path',):
print(" WARNING: --sdk-path is no longer supported")
elif k in ('--src-dir',):
SRCDIR=v
elif k in ('--dep-target', ):
DEPTARGET=v
deptarget=v
elif k in ('--universal-archs', ):
if v in UNIVERSALOPTS:
UNIVERSALARCHS = v
ARCHLIST = universal_opts_map[UNIVERSALARCHS]
if deptarget is None:
# Select alternate default deployment
# target
DEPTARGET = default_target_map.get(v, '10.5')
else:
raise NotImplementedError(v)
else:
raise NotImplementedError(k)
SRCDIR=os.path.abspath(SRCDIR)
WORKDIR=os.path.abspath(WORKDIR)
DEPSRC=os.path.abspath(DEPSRC)
CC, CXX = getTargetCompilers()
FW_VERSION_PREFIX = FW_PREFIX[:] + ["Versions", getVersion()]
FW_SSL_DIRECTORY = FW_VERSION_PREFIX[:] + ["etc", "openssl"]
print("-- Settings:")
print(" * Source directory: %s" % SRCDIR)
print(" * Build directory: %s" % WORKDIR)
print(" * Third-party source: %s" % DEPSRC)
print(" * Deployment target: %s" % DEPTARGET)
print(" * Universal archs: %s" % str(ARCHLIST))
print(" * C compiler: %s" % CC)
print(" * C++ compiler: %s" % CXX)
print("")
print(" -- Building a Python %s framework at patch level %s"
% (getVersion(), getFullVersion()))
print("")
def extractArchive(builddir, archiveName):
"""
Extract a source archive into 'builddir'. Returns the path of the
extracted archive.
XXX: This function assumes that archives contain a toplevel directory
that is has the same name as the basename of the archive. This is
safe enough for almost anything we use. Unfortunately, it does not
work for current Tcl and Tk source releases where the basename of
the archive ends with "-src" but the uncompressed directory does not.
For now, just special case Tcl and Tk tar.gz downloads.
"""
curdir = os.getcwd()
try:
os.chdir(builddir)
if archiveName.endswith('.tar.gz'):
retval = os.path.basename(archiveName[:-7])
if ((retval.startswith('tcl') or retval.startswith('tk'))
and retval.endswith('-src')):
retval = retval[:-4]
# Strip rcxx suffix from Tcl/Tk release candidates
retval_rc = retval.find('rc')
if retval_rc > 0:
retval = retval[:retval_rc]
if os.path.exists(retval):
shutil.rmtree(retval)
fp = os.popen("tar zxf %s 2>&1"%(shellQuote(archiveName),), 'r')
elif archiveName.endswith('.tar.bz2'):
retval = os.path.basename(archiveName[:-8])
if os.path.exists(retval):
shutil.rmtree(retval)
fp = os.popen("tar jxf %s 2>&1"%(shellQuote(archiveName),), 'r')
elif archiveName.endswith('.tar'):
retval = os.path.basename(archiveName[:-4])
if os.path.exists(retval):
shutil.rmtree(retval)
fp = os.popen("tar xf %s 2>&1"%(shellQuote(archiveName),), 'r')
elif archiveName.endswith('.zip'):
retval = os.path.basename(archiveName[:-4])
if os.path.exists(retval):
shutil.rmtree(retval)
fp = os.popen("unzip %s 2>&1"%(shellQuote(archiveName),), 'r')
data = fp.read()
xit = fp.close()
if xit is not None:
sys.stdout.write(data)
raise RuntimeError("Cannot extract %s"%(archiveName,))
return os.path.join(builddir, retval)
finally:
os.chdir(curdir)
def downloadURL(url, fname):
"""
Download the contents of the url into the file.
"""
fpIn = urllib_request.urlopen(url)
fpOut = open(fname, 'wb')
block = fpIn.read(10240)
try:
while block:
fpOut.write(block)
block = fpIn.read(10240)
fpIn.close()
fpOut.close()
except:
try:
os.unlink(fname)
except OSError:
pass
def verifyThirdPartyFile(url, checksum, fname):
"""
Download file from url to filename fname if it does not already exist.
Abort if file contents does not match supplied md5 checksum.
"""
name = os.path.basename(fname)
if os.path.exists(fname):
print("Using local copy of %s"%(name,))
else:
print("Did not find local copy of %s"%(name,))
print("Downloading %s"%(name,))
downloadURL(url, fname)
print("Archive for %s stored as %s"%(name, fname))
if len(checksum) == 32:
algo = 'md5'
elif len(checksum) == 64:
algo = 'sha256'
else:
raise ValueError(checksum)
if os.system(
'CHECKSUM=$(openssl %s %s) ; test "${CHECKSUM##*= }" = "%s"'
% (algo, shellQuote(fname), checksum) ):
fatal('%s checksum mismatch for file %s' % (algo, fname))
def build_universal_openssl(basedir, archList):
"""
Special case build recipe for universal build of openssl.
The upstream OpenSSL build system does not directly support
OS X universal builds. We need to build each architecture
separately then lipo them together into fat libraries.
"""
# OpenSSL fails to build with Xcode 2.5 (on OS X 10.4).
# If we are building on a 10.4.x or earlier system,
# unilaterally disable assembly code building to avoid the problem.
no_asm = int(platform.release().split(".")[0]) < 9
def build_openssl_arch(archbase, arch):
"Build one architecture of openssl"
arch_opts = {
"i386": ["darwin-i386-cc"],
"x86_64": ["darwin64-x86_64-cc", "enable-ec_nistp_64_gcc_128"],
"arm64": ["darwin64-arm64-cc"],
"ppc": ["darwin-ppc-cc"],
"ppc64": ["darwin64-ppc-cc"],
}
# Somewhere between OpenSSL 1.1.0j and 1.1.1c, changes cause the
# "enable-ec_nistp_64_gcc_128" option to get compile errors when
# building on our 10.6 gcc-4.2 environment. There have been other
# reports of projects running into this when using older compilers.
# So, for now, do not try to use "enable-ec_nistp_64_gcc_128" when
# building for 10.6.
if getDeptargetTuple() == (10, 6):
arch_opts['x86_64'].remove('enable-ec_nistp_64_gcc_128')
configure_opts = [
"no-idea",
"no-mdc2",
"no-rc5",
"no-zlib",
"no-ssl3",
# "enable-unit-test",
"shared",
"--prefix=%s"%os.path.join("/", *FW_VERSION_PREFIX),
"--openssldir=%s"%os.path.join("/", *FW_SSL_DIRECTORY),
]
if no_asm:
configure_opts.append("no-asm")
runCommand(" ".join(["perl", "Configure"]
+ arch_opts[arch] + configure_opts))
runCommand("make depend")
runCommand("make all")
runCommand("make install_sw DESTDIR=%s"%shellQuote(archbase))
# runCommand("make test")
return
srcdir = os.getcwd()
universalbase = os.path.join(srcdir, "..",
os.path.basename(srcdir) + "-universal")
os.mkdir(universalbase)
archbasefws = []
for arch in archList:
# fresh copy of the source tree
archsrc = os.path.join(universalbase, arch, "src")
shutil.copytree(srcdir, archsrc, symlinks=True)
# install base for this arch
archbase = os.path.join(universalbase, arch, "root")
os.mkdir(archbase)
# Python framework base within install_prefix:
# the build will install into this framework..
# This is to ensure that the resulting shared libs have
# the desired real install paths built into them.
archbasefw = os.path.join(archbase, *FW_VERSION_PREFIX)
# build one architecture
os.chdir(archsrc)
build_openssl_arch(archbase, arch)
os.chdir(srcdir)
archbasefws.append(archbasefw)
# copy arch-independent files from last build into the basedir framework
basefw = os.path.join(basedir, *FW_VERSION_PREFIX)
shutil.copytree(
os.path.join(archbasefw, "include", "openssl"),
os.path.join(basefw, "include", "openssl")
)
shlib_version_number = grepValue(os.path.join(archsrc, "Makefile"),
"SHLIB_VERSION_NUMBER")
# e.g. -> "1.0.0"
libcrypto = "libcrypto.dylib"
libcrypto_versioned = libcrypto.replace(".", "."+shlib_version_number+".")
# e.g. -> "libcrypto.1.0.0.dylib"
libssl = "libssl.dylib"
libssl_versioned = libssl.replace(".", "."+shlib_version_number+".")
# e.g. -> "libssl.1.0.0.dylib"
try:
os.mkdir(os.path.join(basefw, "lib"))
except OSError:
pass
# merge the individual arch-dependent shared libs into a fat shared lib
archbasefws.insert(0, basefw)
for (lib_unversioned, lib_versioned) in [
(libcrypto, libcrypto_versioned),
(libssl, libssl_versioned)
]:
runCommand("lipo -create -output " +
" ".join(shellQuote(
os.path.join(fw, "lib", lib_versioned))
for fw in archbasefws))
# and create an unversioned symlink of it
os.symlink(lib_versioned, os.path.join(basefw, "lib", lib_unversioned))
# Create links in the temp include and lib dirs that will be injected
# into the Python build so that setup.py can find them while building
# and the versioned links so that the setup.py post-build import test
# does not fail.
relative_path = os.path.join("..", "..", "..", *FW_VERSION_PREFIX)
for fn in [
["include", "openssl"],
["lib", libcrypto],
["lib", libssl],
["lib", libcrypto_versioned],
["lib", libssl_versioned],
]:
os.symlink(
os.path.join(relative_path, *fn),
os.path.join(basedir, "usr", "local", *fn)
)
return
def buildRecipe(recipe, basedir, archList):
"""
Build software using a recipe. This function does the
'configure;make;make install' dance for C software, with a possibility
to customize this process, basically a poor-mans DarwinPorts.
"""
curdir = os.getcwd()
name = recipe['name']
THIRD_PARTY_LIBS.append(name)
url = recipe['url']
configure = recipe.get('configure', './configure')
buildrecipe = recipe.get('buildrecipe', None)
install = recipe.get('install', 'make && make install DESTDIR=%s'%(
shellQuote(basedir)))
archiveName = os.path.split(url)[-1]
sourceArchive = os.path.join(DEPSRC, archiveName)
if not os.path.exists(DEPSRC):
os.mkdir(DEPSRC)
verifyThirdPartyFile(url, recipe['checksum'], sourceArchive)
print("Extracting archive for %s"%(name,))
buildDir=os.path.join(WORKDIR, '_bld')
if not os.path.exists(buildDir):
os.mkdir(buildDir)
workDir = extractArchive(buildDir, sourceArchive)
os.chdir(workDir)
for patch in recipe.get('patches', ()):
if isinstance(patch, tuple):
url, checksum = patch
fn = os.path.join(DEPSRC, os.path.basename(url))
verifyThirdPartyFile(url, checksum, fn)
else:
# patch is a file in the source directory
fn = os.path.join(curdir, patch)
runCommand('patch -p%s < %s'%(recipe.get('patchlevel', 1),
shellQuote(fn),))
for patchscript in recipe.get('patchscripts', ()):
if isinstance(patchscript, tuple):
url, checksum = patchscript
fn = os.path.join(DEPSRC, os.path.basename(url))
verifyThirdPartyFile(url, checksum, fn)
else:
# patch is a file in the source directory