blob: 070246515388dcaee2d181a69987cfaada34900a [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',
76 'win': 'i586-pc-mingw32msvc',
77 'win64': 'x86_64-pc-mingw32msvc',
78 }[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')
107 toolchain_prefix = 'x86_64-linux'
108 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))
124 ar = os.path.join(toolchain, 'bin', '{}-ar'.format(toolchain_prefix))
125
126 env['AR'] = ar
127 env['CC'] = cc
128 env['CXX'] = cxx
129 if m32:
130 env['CFLAGS'] = '-m32'
131 env['CXXFLAGS'] = '-m32'
132 env['LDFLAGS'] = '-m32'
133
134 env_args = ['env'] + ['='.join([k, v]) for k, v in env.items()]
135 check_call(env_args + configure_args)
136
137
138def build(jobs):
139 """Builds binutils."""
140 check_call(['make', '-j', str(jobs)])
141
142
143def install(jobs):
144 """Installs binutils."""
145 check_call(['make', 'install', '-j', str(jobs)])
146
147
148def dist(dist_dir, base_dir, package_name):
149 """Packages binutils for distribution."""
150 has_pbzip2 = ndk.ext.shutil.which('pbzip2') is not None
151 if has_pbzip2:
152 compress_arg = '--use-compress-prog=pbzip2'
153 else:
154 compress_arg = '-j'
155
156 package_path = os.path.join(dist_dir, package_name + 'tar.bz2')
157 cmd = [
158 'tar', compress_arg, '-cf', package_path, '-C', base_dir, package_name,
159 ]
160 subprocess.check_call(cmd)
161
162
163def parse_args():
164 """Parse command line arguments."""
165 parser = argparse.ArgumentParser()
166
167 parser.add_argument(
168 '--arch', choices=ndk.abis.ALL_ARCHITECTURES, required=True)
169 parser.add_argument(
170 '--host', choices=('darwin', 'linux', 'win', 'win64'), required=True)
171
172 parser.add_argument(
173 '--clean', action='store_true',
174 help='Clean the out directory before building.')
175 parser.add_argument(
176 '-j', '--jobs', type=int, default=multiprocessing.cpu_count(),
177 help='Number of jobs to use when building.')
178
179 return parser.parse_args()
180
181
182def main():
183 """Program entry point."""
184 args = parse_args()
185 logging.basicConfig(level=logging.INFO)
186
187 total_timer = ndk.timer.Timer()
188 total_timer.start()
189
190 out_dir = ndk.paths.get_out_dir()
191 dist_dir = ndk.paths.get_dist_dir(out_dir)
192 base_build_dir = os.path.join(
193 out_dir, 'binutils', args.host, args.arch)
194 build_dir = os.path.join(base_build_dir, 'build')
195 package_name = 'binutils-{}-{}'.format(args.arch, args.host)
196 install_dir = os.path.join(base_build_dir, 'install', package_name)
197 binutils_path = os.path.join(THIS_DIR, 'binutils-2.27')
198
199 did_clean = False
200 clean_timer = ndk.timer.Timer()
201 if args.clean and os.path.exists(build_dir):
202 did_clean = True
203 with clean_timer:
204 rmtree(build_dir)
205
206 if not os.path.exists(build_dir):
207 makedirs(build_dir)
208
209 orig_dir = os.getcwd()
210 chdir(build_dir)
211 try:
212 configure_timer = ndk.timer.Timer()
213 with configure_timer:
214 configure(args.arch, args.host, install_dir, binutils_path)
215
216 build_timer = ndk.timer.Timer()
217 with build_timer:
218 build(args.jobs)
219
220 install_timer = ndk.timer.Timer()
221 with install_timer:
222 install(args.jobs)
223 finally:
224 chdir(orig_dir)
225
226 package_timer = ndk.timer.Timer()
227 with package_timer:
228 dist(dist_dir, os.path.dirname(install_dir), package_name)
229
230 total_timer.finish()
231
232 if did_clean:
233 print('Clean: {}'.format(clean_timer.duration))
234 print('Configure: {}'.format(configure_timer.duration))
235 print('Build: {}'.format(build_timer.duration))
236 print('Install: {}'.format(install_timer.duration))
237 print('Package: {}'.format(package_timer.duration))
238 print('Total: {}'.format(total_timer.duration))
239
240
241if __name__ == '__main__':
242 main()