-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.py
executable file
·1747 lines (1412 loc) · 66.2 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 python
#
# Copyright (C) 2016 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# pylint: disable=not-callable, relative-import, line-too-long
import argparse
import datetime
import glob
import logging
import os
import shutil
import string
import subprocess
import textwrap
import utils
import distutils.spawn
import android_version
from version import Version
import mapfile
ORIG_ENV = dict(os.environ)
# Remove GOMA from our environment for building anything from stage2 onwards,
# since it is using a non-GOMA compiler (from stage1) to do the compilation.
USE_GOMA_FOR_STAGE1 = False
if ('USE_GOMA' in ORIG_ENV) and (ORIG_ENV['USE_GOMA'] is 'true'):
USE_GOMA_FOR_STAGE1 = True
del ORIG_ENV['USE_GOMA']
STAGE2_TARGETS = 'AArch64;ARM'
def logger():
"""Returns the module level logger."""
return logging.getLogger(__name__)
def check_call(cmd, *args, **kwargs):
"""subprocess.check_call with logging."""
logger().info('check_call:%s %s',
datetime.datetime.now().strftime("%H:%M:%S"),
subprocess.list2cmdline(cmd))
subprocess.check_call(cmd, *args, **kwargs)
def check_output(cmd, *args, **kwargs):
"""subprocess.check_output with logging."""
logger().info('check_output:%s %s',
datetime.datetime.now().strftime("%H:%M:%S"),
subprocess.list2cmdline(cmd))
return subprocess.check_output(cmd, *args, **kwargs)
def install_file(src, dst):
"""Proxy for shutil.copy2 with logging and dry-run support."""
logger().info('copy %s %s', src, dst)
shutil.copy2(src, dst)
def remove(path):
"""Proxy for os.remove with logging."""
logger().debug('remove %s', path)
os.remove(path)
def extract_clang_version(clang_install):
version_file = os.path.join(clang_install, 'include', 'clang', 'Basic',
'Version.inc')
return Version(version_file)
def extract_clang_long_version(clang_install):
return extract_clang_version(clang_install).long_version()
def pgo_profdata_filename():
base_revision = android_version.svn_revision.rstrip(string.ascii_lowercase)
return '%s.profdata' % base_revision
def pgo_profdata_file(profdata_file):
profile = utils.android_path('prebuilts', 'clang', 'host', 'linux-x86',
'profiles', profdata_file)
return profile if os.path.exists(profile) else None
def ndk_base():
ndk_version = 'r16'
return utils.android_path('toolchain/prebuilts/ndk', ndk_version)
def android_api(arch, platform=False):
if platform:
return '26'
elif arch in ['arm', 'i386', 'x86']:
return '14'
else:
return '21'
def ndk_path(arch, platform=False):
platform_level = 'android-' + android_api(arch, platform)
return os.path.join(ndk_base(), 'platforms', platform_level)
def ndk_libcxx_headers():
return os.path.join(ndk_base(), 'sources', 'cxx-stl', 'llvm-libc++',
'include')
def ndk_libcxxabi_headers():
return os.path.join(ndk_base(), 'sources', 'cxx-stl', 'llvm-libc++abi',
'include')
def ndk_toolchain_lib(arch, toolchain_root, host_tag):
toolchain_lib = os.path.join(ndk_base(), 'toolchains', toolchain_root,
'prebuilt', 'linux-x86_64', host_tag)
if arch in ['arm', 'i386']:
toolchain_lib = os.path.join(toolchain_lib, 'lib')
else:
toolchain_lib = os.path.join(toolchain_lib, 'lib64')
return toolchain_lib
def support_headers():
return os.path.join(ndk_base(), 'sources', 'android', 'support', 'include')
# This is the baseline stable version of Clang to start our stage-1 build.
def clang_prebuilt_version():
return 'clang-r353983b'
def clang_prebuilt_base_dir():
return utils.android_path('prebuilts/clang/host',
utils.build_os_type(), clang_prebuilt_version())
def clang_prebuilt_bin_dir():
return utils.android_path(clang_prebuilt_base_dir(), 'bin')
def clang_prebuilt_lib_dir():
return utils.android_path(clang_prebuilt_base_dir(), 'lib64')
def arch_from_triple(triple):
arch = triple.split('-')[0]
if arch == 'i686':
arch = 'i386'
return arch
def clang_resource_dir(version, arch):
return os.path.join('lib64', 'clang', version, 'lib', 'linux', arch)
def clang_prebuilt_libcxx_headers():
return utils.android_path(clang_prebuilt_base_dir(), 'include', 'c++', 'v1')
def libcxx_header_dirs(ndk_cxx):
if ndk_cxx:
return [
ndk_libcxx_headers(),
ndk_libcxxabi_headers(),
support_headers()
]
else:
# <prebuilts>/include/c++/v1 includes the cxxabi headers
return [
clang_prebuilt_libcxx_headers(),
utils.android_path('bionic', 'libc', 'include')
]
def cmake_prebuilt_bin_dir():
return utils.android_path('prebuilts/cmake', utils.build_os_type(), 'bin')
def cmake_bin_path():
""" Use host's cmake instead of bundled one """
return distutils.spawn.find_executable("cmake")
def ninja_bin_path():
""" Use host's ninja instead of bundled one """
return distutils.spawn.find_executable("ninja")
def check_create_path(path):
if not os.path.exists(path):
os.makedirs(path)
def get_sysroot(arch, platform=False):
sysroots = utils.out_path('sysroots')
platform_or_ndk = 'platform' if platform else 'ndk'
return os.path.join(sysroots, platform_or_ndk, arch)
def debug_prefix_flag():
return '-fdebug-prefix-map={}='.format(utils.android_path())
def create_sysroots():
# Construct the sysroots from scratch, since symlinks can't nest within
# the right places (without altering source prebuilts).
configs = [
('arm', 'arm-linux-androideabi'),
('arm64', 'aarch64-linux-android'),
]
# TODO(srhines): We destroy and recreate the sysroots each time, but this
# could check for differences and only replace files if needed.
sysroots_out = utils.out_path('sysroots')
if os.path.exists(sysroots_out):
shutil.rmtree(sysroots_out)
check_create_path(sysroots_out)
base_header_path = os.path.join(ndk_base(), 'sysroot', 'usr', 'include')
for (arch, target) in configs:
# Also create sysroots for each of platform and the NDK.
for platform_or_ndk in ['platform', 'ndk']:
platform = platform_or_ndk == 'platform'
base_lib_path = \
utils.android_path(ndk_base(), 'platforms',
'android-' + android_api(arch, platform))
dest_usr = os.path.join(get_sysroot(arch, platform), 'usr')
# Copy over usr/include.
dest_usr_include = os.path.join(dest_usr, 'include')
shutil.copytree(base_header_path, dest_usr_include, symlinks=True)
# Copy over usr/include/asm.
asm_headers = os.path.join(base_header_path, target, 'asm')
dest_usr_include_asm = os.path.join(dest_usr_include, 'asm')
shutil.copytree(asm_headers, dest_usr_include_asm, symlinks=True)
# Copy over usr/lib.
arch_lib_path = os.path.join(base_lib_path, 'arch-' + arch,
'usr', 'lib')
dest_usr_lib = os.path.join(dest_usr, 'lib')
shutil.copytree(arch_lib_path, dest_usr_lib, symlinks=True)
# For only x86_64, we also need to copy over usr/lib64
if arch == 'x86_64':
arch_lib64_path = os.path.join(base_lib_path, 'arch-' + arch,
'usr', 'lib64')
dest_usr_lib64 = os.path.join(dest_usr, 'lib64')
shutil.copytree(arch_lib64_path, dest_usr_lib64, symlinks=True)
if platform:
# Create a stub library for the platform's libc++.
platform_stubs = utils.out_path('platform_stubs', arch)
check_create_path(platform_stubs)
libdir = dest_usr_lib64 if arch == 'x86_64' else dest_usr_lib
with open(os.path.join(platform_stubs, 'libc++.c'), 'w') as f:
f.write(textwrap.dedent("""\
void __cxa_atexit() {}
void __cxa_demangle() {}
void __cxa_finalize() {}
void __dynamic_cast() {}
void _ZTIN10__cxxabiv117__class_type_infoE() {}
void _ZTIN10__cxxabiv120__si_class_type_infoE() {}
void _ZTIN10__cxxabiv121__vmi_class_type_infoE() {}
void _ZTISt9type_info() {}
"""))
check_call([utils.out_path('stage2-install', 'bin', 'clang'),
'--target=' + target,
'-fuse-ld=lld', '-nostdlib', '-shared',
'-Wl,-soname,libc++.so',
'-o', os.path.join(libdir, 'libc++.so'),
os.path.join(platform_stubs, 'libc++.c')])
# For arm64 and x86_64, build static cxxabi library from
# toolchain/libcxxabi and use it when building runtimes. This
# should affect all compiler-rt runtimes that use libcxxabi
# (e.g. asan, hwasan, scudo, tsan, ubsan, xray).
if arch not in ('arm64', 'x86_64'):
with open(os.path.join(libdir, 'libc++abi.so'), 'w') as f:
f.write('INPUT(-lc++)')
else:
# We can build libcxxabi only after the sysroots are
# created. Build it for the current arch and copy it to
# <libdir>.
out_dir = build_libcxxabi(utils.out_path('stage2-install'), arch)
out_path = utils.out_path(out_dir, 'lib64', 'libc++abi.a')
shutil.copy2(out_path, os.path.join(libdir))
def update_cmake_sysroot_flags(defines, sysroot):
defines['CMAKE_SYSROOT'] = sysroot
defines['CMAKE_FIND_ROOT_PATH_MODE_INCLUDE'] = 'ONLY'
defines['CMAKE_FIND_ROOT_PATH_MODE_LIBRARY'] = 'ONLY'
defines['CMAKE_FIND_ROOT_PATH_MODE_PACKAGE'] = 'ONLY'
defines['CMAKE_FIND_ROOT_PATH_MODE_PROGRAM'] = 'NEVER'
def rm_cmake_cache(cacheDir):
for dirpath, dirs, files in os.walk(cacheDir): # pylint: disable=not-an-iterable
if 'CMakeCache.txt' in files:
os.remove(os.path.join(dirpath, 'CMakeCache.txt'))
if 'CMakeFiles' in dirs:
utils.rm_tree(os.path.join(dirpath, 'CMakeFiles'))
# Base cmake options such as build type that are common across all invocations
def base_cmake_defines():
defines = {}
defines['CMAKE_BUILD_TYPE'] = 'Release'
defines['LLVM_ENABLE_ASSERTIONS'] = 'OFF'
# https://github.com/android-ndk/ndk/issues/574 - Don't depend on libtinfo.
defines['LLVM_ENABLE_TERMINFO'] = 'OFF'
defines['LLVM_ENABLE_THREADS'] = 'ON'
defines['LLVM_LIBDIR_SUFFIX'] = '64'
defines['LLVM_VERSION_PATCH'] = android_version.patch_level
defines['CLANG_VERSION_PATCHLEVEL'] = android_version.patch_level
defines['CLANG_REPOSITORY_STRING'] = 'https://android.googlesource.com/toolchain/clang'
defines['LLVM_REPOSITORY_STRING'] = 'https://android.googlesource.com/toolchain/llvm'
defines['BUG_REPORT_URL'] = 'https://github.com/android-ndk/ndk/issues'
# http://b/111885871 - Disable building xray because of MacOS issues.
defines['COMPILER_RT_BUILD_XRAY'] = 'OFF'
return defines
def invoke_cmake(out_path, defines, env, cmake_path, target=None, install=True):
flags = ['-G', 'Ninja']
# Specify CMAKE_PREFIX_PATH so 'cmake -G Ninja ...' can find the ninja
# executable.
for key in defines:
newdef = '-D' + key + '=' + defines[key]
flags += [newdef]
flags += [cmake_path]
check_create_path(out_path)
# TODO(srhines): Enable this with a flag, because it forces clean builds
# due to the updated cmake generated files.
#rm_cmake_cache(out_path)
if target:
ninja_target = [target]
else:
ninja_target = []
check_call([cmake_bin_path()] + flags, cwd=out_path, env=env)
check_call([ninja_bin_path()] + ninja_target, cwd=out_path, env=env)
if install:
check_call([ninja_bin_path(), 'install'], cwd=out_path, env=env)
def cross_compile_configs(stage2_install, platform=False):
configs = [
('arm', 'arm', 'arm/arm-linux-androideabi-4.9/arm-linux-androideabi',
'arm-linux-android', '-march=armv7-a'),
('aarch64', 'arm64',
'aarch64/aarch64-linux-android-4.9/aarch64-linux-android',
'aarch64-linux-android', ''),
]
cc = os.path.join(stage2_install, 'bin', 'clang')
cxx = os.path.join(stage2_install, 'bin', 'clang++')
for (arch, ndk_arch, toolchain_path, llvm_triple, extra_flags) in configs:
toolchain_root = utils.android_path('prebuilts/gcc',
utils.build_os_type())
toolchain_bin = os.path.join(toolchain_root, toolchain_path, 'bin')
sysroot = get_sysroot(ndk_arch, platform)
defines = {}
defines['CMAKE_C_COMPILER'] = cc
defines['CMAKE_CXX_COMPILER'] = cxx
# Include the directory with libgcc.a to the linker search path.
toolchain_builtins = os.path.join(
toolchain_root, toolchain_path, '..', 'lib', 'gcc',
os.path.basename(toolchain_path), '4.9.x')
# The 32-bit libgcc.a is sometimes in a separate subdir
if arch == 'i386':
toolchain_builtins = os.path.join(toolchain_builtins, '32')
if ndk_arch == 'arm':
toolchain_lib = ndk_toolchain_lib(arch, 'arm-linux-androideabi-4.9',
'arm-linux-androideabi')
elif ndk_arch == 'x86' or ndk_arch == 'x86_64':
toolchain_lib = ndk_toolchain_lib(arch, ndk_arch + '-4.9',
llvm_triple)
else:
toolchain_lib = ndk_toolchain_lib(arch, llvm_triple + '-4.9',
llvm_triple)
ldflags = [
'-L' + toolchain_builtins, '-Wl,-z,defs',
'-L' + toolchain_lib,
'-fuse-ld=lld',
'-Wl,--gc-sections',
'-Wl,--build-id=sha1',
]
if not platform:
libcxx_libs = os.path.join(ndk_base(), 'sources', 'cxx-stl',
'llvm-libc++', 'libs')
if ndk_arch == 'arm':
libcxx_libs = os.path.join(libcxx_libs, 'armeabi')
elif ndk_arch == 'arm64':
libcxx_libs = os.path.join(libcxx_libs, 'arm64-v8a')
else:
libcxx_libs = os.path.join(libcxx_libs, ndk_arch)
ldflags += ['-L', libcxx_libs]
defines['CMAKE_EXE_LINKER_FLAGS'] = ' '.join(ldflags)
defines['CMAKE_SHARED_LINKER_FLAGS'] = ' '.join(ldflags)
defines['CMAKE_MODULE_LINKER_FLAGS'] = ' '.join(ldflags)
update_cmake_sysroot_flags(defines, sysroot)
cflags = [
debug_prefix_flag(),
'--target=%s' % llvm_triple,
'-B%s' % toolchain_bin,
'-D__ANDROID_API__=%s' % android_api(arch, platform=platform),
'-ffunction-sections',
'-fdata-sections',
extra_flags,
]
yield (arch, llvm_triple, defines, cflags)
def build_asan_test(stage2_install):
# We can not build asan_test using current CMake building system. Since
# those files are not used to build AOSP, we just simply touch them so that
# we can pass the build checks.
for arch in ('aarch64', 'arm', 'i686'):
asan_test_path = os.path.join(stage2_install, 'test', arch, 'bin')
check_create_path(asan_test_path)
asan_test_bin_path = os.path.join(asan_test_path, 'asan_test')
open(asan_test_bin_path, 'w+').close()
def build_sanitizer_map_file(san, arch, lib_dir):
lib_file = os.path.join(lib_dir, 'libclang_rt.{}-{}-android.so'.format(san, arch))
map_file = os.path.join(lib_dir, 'libclang_rt.{}-{}-android.map.txt'.format(san, arch))
mapfile.create_map_file(lib_file, map_file)
def build_sanitizer_map_files(stage2_install, clang_version):
lib_dir = os.path.join(stage2_install,
clang_resource_dir(clang_version.long_version(), ''))
for arch in ('aarch64', 'arm'):
build_sanitizer_map_file('asan', arch, lib_dir)
build_sanitizer_map_file('hwasan', 'aarch64', lib_dir)
def create_hwasan_symlink(stage2_install, clang_version):
lib_dir = os.path.join(stage2_install,
clang_resource_dir(clang_version.long_version(), ''))
os.symlink('libclang_rt.hwasan-aarch64-android.a',
lib_dir + 'libclang_rt.hwasan_static-aarch64-android.a')
def build_libcxx(stage2_install, clang_version):
for (arch, llvm_triple, libcxx_defines,
cflags) in cross_compile_configs(stage2_install): # pylint: disable=not-an-iterable
logger().info('Building libcxx for %s', arch)
libcxx_path = utils.out_path('lib', 'libcxx-' + arch)
libcxx_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)
libcxx_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
libcxx_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)
libcxx_defines['CMAKE_BUILD_TYPE'] = 'Release'
libcxx_env = dict(ORIG_ENV)
libcxx_cmake_path = utils.llvm_path('projects', 'libcxx')
rm_cmake_cache(libcxx_path)
invoke_cmake(
out_path=libcxx_path,
defines=libcxx_defines,
env=libcxx_env,
cmake_path=libcxx_cmake_path,
install=False)
# We need to install libcxx manually.
install_subdir = clang_resource_dir(clang_version.long_version(),
arch_from_triple(llvm_triple))
libcxx_install = os.path.join(stage2_install, install_subdir)
libcxx_libs = os.path.join(libcxx_path, 'lib')
check_create_path(libcxx_install)
for f in os.listdir(libcxx_libs):
if f.startswith('libc++'):
shutil.copy2(os.path.join(libcxx_libs, f), libcxx_install)
def build_crts(stage2_install, clang_version, ndk_cxx=False):
llvm_config = os.path.join(stage2_install, 'bin', 'llvm-config')
# Now build compiler-rt for each arch
for (arch, llvm_triple, crt_defines,
cflags) in cross_compile_configs(stage2_install, platform=(not ndk_cxx)): # pylint: disable=not-an-iterable
logger().info('Building compiler-rt for %s', arch)
crt_path = utils.out_path('lib', 'clangrt-' + arch)
crt_install = os.path.join(stage2_install, 'lib64', 'clang',
clang_version.long_version())
if ndk_cxx:
crt_path += '-ndk-cxx'
crt_install = crt_path + '-install'
crt_defines['ANDROID'] = '1'
crt_defines['LLVM_CONFIG_PATH'] = llvm_config
crt_defines['COMPILER_RT_INCLUDE_TESTS'] = 'ON'
# FIXME: Disable WError build until upstream fixed the compiler-rt
# personality routine warnings caused by r309226.
# crt_defines['COMPILER_RT_ENABLE_WERROR'] = 'ON'
cflags.append('-isystem ' + support_headers())
cflags.append('-funwind-tables')
crt_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
crt_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)
crt_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)
crt_defines['COMPILER_RT_TEST_COMPILER_CFLAGS'] = ' '.join(cflags)
crt_defines['COMPILER_RT_TEST_TARGET_TRIPLE'] = llvm_triple
crt_defines['COMPILER_RT_INCLUDE_TESTS'] = 'OFF'
crt_defines['CMAKE_INSTALL_PREFIX'] = crt_install
# Build libfuzzer separately.
crt_defines['COMPILER_RT_BUILD_LIBFUZZER'] = 'OFF'
crt_defines['SANITIZER_CXX_ABI'] = 'libcxxabi'
libs = []
if arch == 'arm':
libs += ['-latomic']
if ndk_cxx:
libs += ['-landroid_support']
crt_defines['SANITIZER_COMMON_LINK_LIBS'] = ' '.join(libs)
if not ndk_cxx:
crt_defines['COMPILER_RT_HWASAN_WITH_INTERCEPTORS'] = 'OFF'
crt_defines.update(base_cmake_defines())
crt_env = dict(ORIG_ENV)
crt_cmake_path = utils.llvm_path('projects', 'compiler-rt')
rm_cmake_cache(crt_path)
invoke_cmake(
out_path=crt_path,
defines=crt_defines,
env=crt_env,
cmake_path=crt_cmake_path)
if ndk_cxx:
src_dir = os.path.join(crt_install, 'lib', 'linux')
dst_dir = os.path.join(stage2_install, 'runtimes_ndk_cxx')
check_create_path(dst_dir)
for f in os.listdir(src_dir):
shutil.copy2(os.path.join(src_dir, f), os.path.join(dst_dir, f))
def build_libfuzzers(stage2_install, clang_version, ndk_cxx=False):
llvm_config = os.path.join(stage2_install, 'bin', 'llvm-config')
for (arch, llvm_triple, libfuzzer_defines, cflags) in cross_compile_configs( # pylint: disable=not-an-iterable
stage2_install, platform=(not ndk_cxx)):
logger().info('Building libfuzzer for %s (ndk_cxx? %s)', arch, ndk_cxx)
libfuzzer_path = utils.out_path('lib', 'libfuzzer-' + arch)
if ndk_cxx:
libfuzzer_path += '-ndk-cxx'
libfuzzer_defines['ANDROID'] = '1'
libfuzzer_defines['LLVM_CONFIG_PATH'] = llvm_config
cflags.extend('-isystem ' + d for d in libcxx_header_dirs(ndk_cxx))
libfuzzer_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)
libfuzzer_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
libfuzzer_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)
if ndk_cxx:
libfuzzer_defines['CMAKE_CXX_FLAGS'] += ' -stdlib=libstdc++'
# lib/Fuzzer/CMakeLists.txt does not call cmake_minimum_required() to
# set a minimum version. Explicitly request a policy that'll pass
# CMAKE_*_LINKER_FLAGS to the trycompile() step.
libfuzzer_defines['CMAKE_POLICY_DEFAULT_CMP0056'] = 'NEW'
libfuzzer_cmake_path = utils.llvm_path('projects', 'compiler-rt')
libfuzzer_env = dict(ORIG_ENV)
rm_cmake_cache(libfuzzer_path)
invoke_cmake(
out_path=libfuzzer_path,
defines=libfuzzer_defines,
env=libfuzzer_env,
cmake_path=libfuzzer_cmake_path,
target='fuzzer',
install=False)
# We need to install libfuzzer manually.
sarch = arch
if sarch == 'i386':
sarch = 'i686'
static_lib_filename = 'libclang_rt.fuzzer-' + sarch + '-android.a'
static_lib = os.path.join(libfuzzer_path, 'lib', 'linux', static_lib_filename)
triple_arch = arch_from_triple(llvm_triple)
if ndk_cxx:
lib_subdir = os.path.join('runtimes_ndk_cxx', triple_arch)
else:
lib_subdir = clang_resource_dir(clang_version.long_version(),
triple_arch)
lib_dir = os.path.join(stage2_install, lib_subdir)
check_create_path(lib_dir)
shutil.copy2(static_lib, os.path.join(lib_dir, 'libFuzzer.a'))
# Install libfuzzer headers.
header_src = utils.llvm_path('projects', 'compiler-rt', 'lib', 'fuzzer')
header_dst = os.path.join(stage2_install, 'prebuilt_include', 'llvm', 'lib',
'Fuzzer')
check_create_path(header_dst)
for f in os.listdir(header_src):
if f.endswith('.h') or f.endswith('.def'):
shutil.copy2(os.path.join(header_src, f), header_dst)
def build_libcxxabi(stage2_install, build_arch):
# Normalize arm64/aarch64
if build_arch == 'arm64':
build_arch = 'aarch64'
# TODO: Refactor cross_compile_configs to support per-arch queries in
# addition to being a generator.
for (arch, llvm_triple, defines, cflags) in \
cross_compile_configs(stage2_install, platform=True): # pylint: disable=not-an-iterable
# Build only the requested arch.
if arch != build_arch:
continue
logger().info('Building libcxxabi for %s', arch)
defines['LIBCXXABI_LIBCXX_INCLUDES'] = utils.android_path('toolchain', 'libcxx', 'include')
defines['LIBCXXABI_ENABLE_SHARED'] = 'OFF'
defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)
out_path = utils.out_path('lib', 'libcxxabi-' + arch)
if os.path.exists(out_path):
utils.rm_tree(out_path)
invoke_cmake(out_path=out_path,
defines=defines,
env=dict(ORIG_ENV),
cmake_path=utils.android_path('toolchain', 'libcxxabi'),
install=False)
return out_path
def build_libomp(stage2_install, clang_version, ndk_cxx=False):
for (arch, llvm_triple, libomp_defines, cflags) in cross_compile_configs( # pylint: disable=not-an-iterable
stage2_install, platform=(not ndk_cxx)):
logger().info('Building libomp for %s (ndk_cxx? %s)', arch, ndk_cxx)
cflags.extend('-isystem ' + d for d in libcxx_header_dirs(ndk_cxx))
cflags.append('-fPIC')
libomp_path = utils.out_path('lib', 'libomp-' + arch)
if ndk_cxx:
libomp_path += '-ndk-cxx'
libomp_defines['ANDROID'] = '1'
libomp_defines['CMAKE_BUILD_TYPE'] = 'Release'
libomp_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)
libomp_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
libomp_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags) + ' -stdlib=libstdc++'
libomp_defines['LIBOMP_ENABLE_SHARED'] = 'FALSE'
libomp_defines['OPENMP_ENABLE_LIBOMPTARGET'] = 'FALSE'
# Minimum version for OpenMP's CMake is too low for the CMP0056 policy
# to be ON by default.
libomp_defines['CMAKE_POLICY_DEFAULT_CMP0056'] = 'NEW'
libomp_cmake_path = utils.llvm_path('projects', 'openmp')
libomp_env = dict(ORIG_ENV)
rm_cmake_cache(libomp_path)
invoke_cmake(
out_path=libomp_path,
defines=libomp_defines,
env=libomp_env,
cmake_path=libomp_cmake_path,
install=False)
# We need to install libomp manually.
static_lib = os.path.join(libomp_path, 'runtime', 'src', 'libomp.a')
triple_arch = arch_from_triple(llvm_triple)
if ndk_cxx:
lib_subdir = os.path.join('runtimes_ndk_cxx', triple_arch)
else:
lib_subdir = clang_resource_dir(clang_version.long_version(),
triple_arch)
lib_dir = os.path.join(stage2_install, lib_subdir)
check_create_path(lib_dir)
shutil.copy2(static_lib, os.path.join(lib_dir, 'libomp.a'))
def build_crts_host_i686(stage2_install, clang_version):
logger().info('Building compiler-rt for host-i686')
llvm_config = os.path.join(stage2_install, 'bin', 'llvm-config')
crt_install = os.path.join(stage2_install, 'lib64', 'clang',
clang_version.long_version())
crt_cmake_path = utils.llvm_path('projects', 'compiler-rt')
cflags, ldflags = host_gcc_toolchain_flags(utils.build_os_type(), is_32_bit=True)
crt_defines = base_cmake_defines()
crt_defines['CMAKE_C_COMPILER'] = os.path.join(stage2_install, 'bin',
'clang')
crt_defines['CMAKE_CXX_COMPILER'] = os.path.join(stage2_install, 'bin',
'clang++')
# Skip building runtimes for i386
crt_defines['COMPILER_RT_DEFAULT_TARGET_ONLY'] = 'ON'
# Due to CMake and Clang oddities, we need to explicitly set
# CMAKE_C_COMPILER_TARGET and use march=i686 in cflags below instead of
# relying on auto-detection from the Compiler-rt CMake files.
crt_defines['CMAKE_C_COMPILER_TARGET'] = 'i386-linux-gnu'
crt_defines['CMAKE_SYSROOT'] = host_sysroot()
cflags.append('--target=i386-linux-gnu')
cflags.append('-march=i686')
crt_defines['LLVM_CONFIG_PATH'] = llvm_config
crt_defines['COMPILER_RT_INCLUDE_TESTS'] = 'ON'
crt_defines['COMPILER_RT_ENABLE_WERROR'] = 'ON'
crt_defines['CMAKE_INSTALL_PREFIX'] = crt_install
crt_defines['SANITIZER_CXX_ABI'] = 'libstdc++'
crt_defines['COMPILER_RT_BUILD_LIBFUZZER'] = 'OFF'
# Set the compiler and linker flags
crt_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)
crt_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
crt_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)
crt_defines['CMAKE_EXE_LINKER_FLAGS'] = ' '.join(ldflags)
crt_defines['CMAKE_SHARED_LINKER_FLAGS'] = ' '.join(ldflags)
crt_defines['CMAKE_MODULE_LINKER_FLAGS'] = ' '.join(ldflags)
crt_env = dict(ORIG_ENV)
crt_path = utils.out_path('lib', 'clangrt-i386-host')
rm_cmake_cache(crt_path)
invoke_cmake(
out_path=crt_path,
defines=crt_defines,
env=crt_env,
cmake_path=crt_cmake_path)
def build_llvm(targets,
build_dir,
install_dir,
build_name,
extra_defines=None,
extra_env=None):
cmake_defines = base_cmake_defines()
cmake_defines['CMAKE_INSTALL_PREFIX'] = install_dir
cmake_defines['LLVM_TARGETS_TO_BUILD'] = targets
cmake_defines['LLVM_BUILD_LLVM_DYLIB'] = 'ON'
cmake_defines['CLANG_VENDOR'] = 'Android (' + build_name + ' based on ' + \
android_version.svn_revision + ') '
cmake_defines['LLVM_BINUTILS_INCDIR'] = utils.android_path(
'toolchain/binutils/binutils-2.27/include')
if extra_defines is not None:
cmake_defines.update(extra_defines)
env = dict(ORIG_ENV)
if extra_env is not None:
env.update(extra_env)
invoke_cmake(
out_path=build_dir,
defines=cmake_defines,
env=env,
cmake_path=utils.llvm_path())
def windows_cflags(is_32_bit):
triple = 'i686-windows-gnu' if is_32_bit else 'x86_64-pc-windows-gnu'
cflags = ['--target='+triple, '-D_LARGEFILE_SOURCE', '-D_FILE_OFFSET_BITS=64',
'-D_WIN32_WINNT=0x0600', '-DWINVER=0x0600',
'-D__MSVCRT_VERSION__=0x1400']
# Use sjlj exceptions, the model implemented in 32-bit libgcc_eh
if is_32_bit:
cflags.append('-fsjlj-exceptions')
return cflags
def build_libs_for_windows(libname,
enable_assertions,
install_dir,
is_32_bit=False):
cflags, ldflags = host_gcc_toolchain_flags('windows-x86', is_32_bit)
cflags.extend(windows_cflags(is_32_bit))
cmake_defines = dict()
cmake_defines['CMAKE_SYSTEM_NAME'] = 'Windows'
cmake_defines['CMAKE_C_COMPILER'] = os.path.join(
clang_prebuilt_bin_dir(), 'clang')
cmake_defines['CMAKE_CXX_COMPILER'] = os.path.join(
clang_prebuilt_bin_dir(), 'clang++')
windows_sysroot = utils.android_path('prebuilts', 'gcc', 'linux-x86', 'host',
'x86_64-w64-mingw32-4.8',
'x86_64-w64-mingw32')
update_cmake_sysroot_flags(cmake_defines, windows_sysroot)
# Build only the static library.
cmake_defines[libname.upper() + '_ENABLE_SHARED'] = 'OFF'
if enable_assertions:
cmake_defines[libname.upper() + '_ENABLE_ASSERTIONS'] = 'ON'
if libname == 'libcxx':
cmake_defines['LIBCXX_ENABLE_STATIC_ABI_LIBRARY'] = 'ON'
cmake_defines['LIBCXX_CXX_ABI'] = 'libcxxabi'
cmake_defines['LIBCXX_HAS_WIN32_THREAD_API'] = 'ON'
# Use cxxabi header from the source directory since it gets installed
# into install_dir only during libcxx's install step. But use the
# library from install_dir.
cmake_defines['LIBCXX_CXX_ABI_INCLUDE_PATHS'] = utils.android_path('toolchain', 'libcxxabi', 'include')
cmake_defines['LIBCXX_CXX_ABI_LIBRARY_PATH'] = os.path.join(install_dir, 'lib')
# Disable libcxxabi visibility annotations since we're only building it
# statically.
cflags.append('-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS')
elif libname == 'libcxxabi':
cmake_defines['LIBCXXABI_ENABLE_NEW_DELETE_DEFINITIONS'] = 'OFF'
cmake_defines['LIBCXXABI_LIBCXX_INCLUDES'] = utils.android_path('toolchain', 'libcxx', 'include')
# Disable libcxx visibility annotations and enable WIN32 threads. These
# are needed because the libcxxabi build happens before libcxx and uses
# headers directly from the sources.
cflags.append('-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS')
cflags.append('-D_LIBCPP_HAS_THREAD_API_WIN32')
cmake_defines['CMAKE_INSTALL_PREFIX'] = install_dir
cmake_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)
cmake_defines['CMAKE_CXX_FLAGS'] = ' '.join(cflags)
cmake_defines['CMAKE_EXE_LINKER_FLAGS'] = ' '.join(ldflags)
cmake_defines['CMAKE_SHARED_LINKER_FLAGS'] = ' '.join(ldflags)
cmake_defines['CMAKE_MODULE_LINKER_FLAGS'] = ' '.join(ldflags)
out_path = utils.out_path('lib', 'windows-' + libname)
if is_32_bit:
out_path += '-32'
if os.path.exists(out_path):
utils.rm_tree(out_path)
invoke_cmake(out_path=out_path,
defines=cmake_defines,
env=dict(ORIG_ENV),
cmake_path=utils.android_path('toolchain', libname),
install=True)
def build_llvm_for_windows(stage1_install,
targets,
enable_assertions,
build_dir,
install_dir,
build_name,
is_32_bit=False):
# Build and install libcxxabi and libcxx and use them to build Clang.
build_libs_for_windows('libcxxabi',
enable_assertions,
install_dir,
is_32_bit)
build_libs_for_windows('libcxx',
enable_assertions,
install_dir,
is_32_bit)
# Write a NATIVE.cmake in windows_path that contains the compilers used
# to build native tools such as llvm-tblgen and llvm-config. This is
# used below via the CMake variable CROSS_TOOLCHAIN_FLAGS_NATIVE.
cc = os.path.join(stage1_install, 'bin', 'clang')
cxx = os.path.join(stage1_install, 'bin', 'clang++')
check_create_path(build_dir)
native_cmake_file_path = os.path.join(build_dir, 'NATIVE.cmake')
native_cmake_text = ('set(CMAKE_C_COMPILER {cc})\n'
'set(CMAKE_CXX_COMPILER {cxx})\n').format(
cc=cc, cxx=cxx)
with open(native_cmake_file_path, 'w') as native_cmake_file:
native_cmake_file.write(native_cmake_text)
# Extra cmake defines to use while building for Windows
windows_extra_defines = dict()
windows_extra_defines['CMAKE_C_COMPILER'] = cc
windows_extra_defines['CMAKE_CXX_COMPILER'] = cxx
windows_extra_defines['CMAKE_SYSTEM_NAME'] = 'Windows'
# Don't build compiler-rt, libcxx etc. for Windows
windows_extra_defines['LLVM_BUILD_RUNTIME'] = 'OFF'
# Build clang-tidy/clang-format for Windows.
windows_extra_defines['LLVM_TOOL_CLANG_TOOLS_EXTRA_BUILD'] = 'ON'
windows_extra_defines['LLVM_TOOL_OPENMP_BUILD'] = 'OFF'
# Don't build tests for Windows.
windows_extra_defines['LLVM_INCLUDE_TESTS'] = 'OFF'
# Use libc++ for Windows.
windows_extra_defines['LLVM_ENABLE_LIBCXX'] = 'ON'
# Do not build LLVM.dll, which cannot build with lld because lld doesn't
# silently ignore --version-script for Windows. It's not necessary for the
# Android toolchain anyway.
windows_extra_defines['LLVM_BUILD_LLVM_DYLIB'] = 'OFF'
windows_sysroot = utils.android_path('prebuilts', 'gcc', 'linux-x86',
'host', 'x86_64-w64-mingw32-4.8',
'x86_64-w64-mingw32')
update_cmake_sysroot_flags(windows_extra_defines, windows_sysroot)
# Set CMake path, toolchain file for native compilation (to build tablegen
# etc). Also disable libfuzzer build during native compilation.
windows_extra_defines['CROSS_TOOLCHAIN_FLAGS_NATIVE'] = \
'-DCMAKE_PREFIX_PATH=' + cmake_prebuilt_bin_dir() + ';' + \
'-DCOMPILER_RT_BUILD_LIBFUZZER=OFF;'+ \
'-DCMAKE_TOOLCHAIN_FILE=' + native_cmake_file_path
if enable_assertions:
windows_extra_defines['LLVM_ENABLE_ASSERTIONS'] = 'ON'
cflags, ldflags = host_gcc_toolchain_flags('windows-x86', is_32_bit)
cflags.extend(windows_cflags(is_32_bit))
cxxflags = list(cflags)
# Use -fuse-cxa-atexit to allow static TLS destructors. This is needed for
# clang-tools-extra/clangd/Context.cpp
cxxflags.append('-fuse-cxa-atexit')
# Explicitly add the path to libc++ headers. We don't need to configure
# options like visibility annotations, win32 threads etc. because the
# __generated_config header in the patch captures all the options used when
# building libc++.
cxxflags.extend(('-I', os.path.join(install_dir, 'include', 'c++', 'v1')))
ldflags.extend((
'-Wl,--dynamicbase',
'-Wl,--nxcompat',
# Use ucrt to find locale functions needed by libc++.
'-lucrt', '-lucrtbase',
# Use static-libgcc to avoid runtime dependence on libgcc_eh.
'-static-libgcc',
# pthread is needed by libgcc_eh
'-lpthread',
# Add path to libc++, libc++abi.
'-L', os.path.join(install_dir, 'lib')))
if is_32_bit:
# 32-bit libraries belong in lib/.
windows_extra_defines['LLVM_LIBDIR_SUFFIX'] = ''
else:
ldflags.append('-Wl,--high-entropy-va')
# Include zlib's header and library path
zlib_path = utils.android_path('prebuilts', 'clang', 'host', 'windows-x86',
'toolchain-prebuilts', 'zlib')
if is_32_bit:
zlib_path = zlib_path.replace('windows-x86', 'windows-x86_32')
zlib_inc = os.path.join(zlib_path, 'include')
zlib_lib = os.path.join(zlib_path, 'lib')
cflags.extend(['-I', zlib_inc])
cxxflags.extend(['-I', zlib_inc])
ldflags.extend(['-L', zlib_lib])
windows_extra_defines['CMAKE_ASM_FLAGS'] = ' '.join(cflags)
windows_extra_defines['CMAKE_C_FLAGS'] = ' '.join(cflags)