blob: 840ba56a8257be62f771793ac30ced73d5646c0d [file] [log] [blame]
Dan Albert70a30b52017-07-25 14:49:43 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2017 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
17"""Builds binutils."""
18from __future__ import print_function
19
20import argparse
21import logging
22import multiprocessing
23import os
24import shutil
25import site
26import subprocess
27
28
29THIS_DIR = os.path.realpath(os.path.dirname(__file__))
30site.addsitedir(os.path.join(THIS_DIR, '../../ndk'))
31
32# pylint: disable=wrong-import-position
33import ndk.abis # pylint: disable=import-error
34import ndk.ext.shutil # pylint: disable=import-error
35import ndk.paths # pylint: disable=import-error
36import ndk.timer # pylint: disable=import-error
37# pylint: enable=wrong-import-position
38
39
40def logger():
41 """Returns the module level logger."""
42 return logging.getLogger(__name__)
43
44
45def makedirs(path):
46 """os.makedirs with logging."""
47 logger().info('makedirs ' + path)
48 os.makedirs(path)
49
50
51def rmtree(path):
52 """shutil.rmtree with logging."""
53 logger().info('rmtree ' + path)
54 shutil.rmtree(path)
55
56
57def chdir(path):
58 """os.chdir with logging."""
59 logger().info('chdir ' + path)
60 os.chdir(path)
61
62
63def check_call(cmd, *args, **kwargs):
64 """subprocess.check_call with logging."""
65 logger().info('check_call %s', subprocess.list2cmdline(cmd))
66 subprocess.check_call(cmd, *args, **kwargs)
67
68
69def configure(arch, host, install_dir, src_dir):
70 """Configures binutils."""
71 is_windows = host in ('win', 'win64')
72
73 configure_host = {
74 'darwin': 'x86_64-apple-darwin',
75 'linux': 'x86_64-linux-gnu',
Ryan Prichard6fa214b2018-01-22 22:23:52 -080076 'win': 'i686-w64-mingw32',
77 'win64': 'x86_64-w64-mingw32',
Dan Albert70a30b52017-07-25 14:49:43 -070078 }[host]
79
80 sysroot = ndk.paths.sysroot_path(ndk.abis.arch_to_toolchain(arch))
81 configure_args = [
82 os.path.join(src_dir, 'configure'),
83 '--target={}'.format(ndk.abis.arch_to_triple(arch)),
84 '--host={}'.format(configure_host),
85 '--enable-gold=default',
86 '--enable-initfini-array',
87 '--enable-plugins',
88 '--with-sysroot={}'.format(sysroot),
89 '--prefix={}'.format(install_dir),
90 ]
91
92 if arch == 'arm64':
93 configure_args.append('--enable-fix-cortex-a53-835769')
94
95 if not is_windows:
96 # Multithreaded linking is implemented with pthreads, which we
97 # historically couldn't use on Windows.
98 # TODO: Try enabling this now that we have winpthreads in mingw.
99 configure_args.append('--enable-threads')
100
101 env = {}
102
103 m32 = False
104 if host == 'darwin':
105 toolchain = ndk.paths.android_path(
106 'prebuilts/gcc/darwin-x86/host/i686-apple-darwin-4.2.1')
Dan Albert62961252017-12-13 11:44:52 -0800107 toolchain_prefix = 'i686-apple-darwin10'
Dan Albert70a30b52017-07-25 14:49:43 -0700108 env['MACOSX_DEPLOYMENT_TARGET'] = '10.6'
109 elif host == 'linux':
110 toolchain = ndk.paths.android_path(
111 'prebuilts/gcc/linux-x86/host/x86_64-linux-glibc2.11-4.8')
112 toolchain_prefix = 'x86_64-linux'
113 elif is_windows:
114 toolchain = ndk.paths.android_path(
115 'prebuilts/gcc/linux-x86/host/x86_64-w64-mingw32-4.8')
116 toolchain_prefix = 'x86_64-w64-mingw32'
117 if host == 'win':
118 m32 = True
119 else:
120 raise NotImplementedError
121
122 cc = os.path.join(toolchain, 'bin', '{}-gcc'.format(toolchain_prefix))
123 cxx = os.path.join(toolchain, 'bin', '{}-g++'.format(toolchain_prefix))
Dan Albert10af2892017-12-15 12:22:55 -0800124
125 # Our darwin prebuilts are gcc *only*. No binutils.
126 if host == 'darwin':
127 ar = 'ar'
128 strip = 'strip'
129 else:
130 ar = os.path.join(toolchain, 'bin', '{}-ar'.format(toolchain_prefix))
131 strip = os.path.join(
132 toolchain, 'bin', '{}-strip'.format(toolchain_prefix))
Dan Albert70a30b52017-07-25 14:49:43 -0700133
134 env['AR'] = ar
135 env['CC'] = cc
136 env['CXX'] = cxx
Dan Albert08f5b702017-12-12 15:34:41 -0800137 env['STRIP'] = strip
Dan Albert70a30b52017-07-25 14:49:43 -0700138 if m32:
139 env['CFLAGS'] = '-m32'
140 env['CXXFLAGS'] = '-m32'
141 env['LDFLAGS'] = '-m32'
142
143 env_args = ['env'] + ['='.join([k, v]) for k, v in env.items()]
144 check_call(env_args + configure_args)
145
146
147def build(jobs):
148 """Builds binutils."""
149 check_call(['make', '-j', str(jobs)])
150
151
152def install(jobs):
153 """Installs binutils."""
Dan Albert08f5b702017-12-12 15:34:41 -0800154 check_call(['make', 'install-strip', '-j', str(jobs)])
Dan Albert70a30b52017-07-25 14:49:43 -0700155
156
157def dist(dist_dir, base_dir, package_name):
158 """Packages binutils for distribution."""
159 has_pbzip2 = ndk.ext.shutil.which('pbzip2') is not None
160 if has_pbzip2:
161 compress_arg = '--use-compress-prog=pbzip2'
162 else:
163 compress_arg = '-j'
164
Dan Albert45d25132018-01-29 23:31:43 -0800165 package_path = os.path.join(dist_dir, package_name + '.tar.bz2')
Dan Albert70a30b52017-07-25 14:49:43 -0700166 cmd = [
167 'tar', compress_arg, '-cf', package_path, '-C', base_dir, package_name,
168 ]
169 subprocess.check_call(cmd)
170
171
172def parse_args():
173 """Parse command line arguments."""
174 parser = argparse.ArgumentParser()
175
176 parser.add_argument(
177 '--arch', choices=ndk.abis.ALL_ARCHITECTURES, required=True)
178 parser.add_argument(
179 '--host', choices=('darwin', 'linux', 'win', 'win64'), required=True)
180
181 parser.add_argument(
182 '--clean', action='store_true',
183 help='Clean the out directory before building.')
184 parser.add_argument(
185 '-j', '--jobs', type=int, default=multiprocessing.cpu_count(),
186 help='Number of jobs to use when building.')
187
188 return parser.parse_args()
189
190
191def main():
192 """Program entry point."""
193 args = parse_args()
194 logging.basicConfig(level=logging.INFO)
195
196 total_timer = ndk.timer.Timer()
197 total_timer.start()
198
199 out_dir = ndk.paths.get_out_dir()
200 dist_dir = ndk.paths.get_dist_dir(out_dir)
201 base_build_dir = os.path.join(
202 out_dir, 'binutils', args.host, args.arch)
203 build_dir = os.path.join(base_build_dir, 'build')
204 package_name = 'binutils-{}-{}'.format(args.arch, args.host)
205 install_dir = os.path.join(base_build_dir, 'install', package_name)
206 binutils_path = os.path.join(THIS_DIR, 'binutils-2.27')
207
208 did_clean = False
209 clean_timer = ndk.timer.Timer()
210 if args.clean and os.path.exists(build_dir):
211 did_clean = True
212 with clean_timer:
213 rmtree(build_dir)
214
215 if not os.path.exists(build_dir):
216 makedirs(build_dir)
217
218 orig_dir = os.getcwd()
219 chdir(build_dir)
220 try:
221 configure_timer = ndk.timer.Timer()
222 with configure_timer:
223 configure(args.arch, args.host, install_dir, binutils_path)
224
225 build_timer = ndk.timer.Timer()
226 with build_timer:
227 build(args.jobs)
228
229 install_timer = ndk.timer.Timer()
230 with install_timer:
231 install(args.jobs)
232 finally:
233 chdir(orig_dir)
234
235 package_timer = ndk.timer.Timer()
236 with package_timer:
237 dist(dist_dir, os.path.dirname(install_dir), package_name)
238
239 total_timer.finish()
240
241 if did_clean:
242 print('Clean: {}'.format(clean_timer.duration))
243 print('Configure: {}'.format(configure_timer.duration))
244 print('Build: {}'.format(build_timer.duration))
245 print('Install: {}'.format(install_timer.duration))
246 print('Package: {}'.format(package_timer.duration))
247 print('Total: {}'.format(total_timer.duration))
248
249
250if __name__ == '__main__':
251 main()