blob: f5048e02252cf5981270f0c1fb7e54abc21cc0e7 [file] [log] [blame]
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07001#! /usr/bin/env python
2
Duy Truong790f06d2013-02-13 16:38:12 -08003# Copyright (c) 2009-2011, The Linux Foundation. All rights reserved.
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07004#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are met:
7# * Redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer.
9# * Redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution.
Duy Truong790f06d2013-02-13 16:38:12 -080012# * Neither the name of The Linux Foundation nor
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -070013# the names of its contributors may be used to endorse or promote
14# products derived from this software without specific prior written
15# permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19# IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20# NON-INFRINGEMENT ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
21# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
22# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
24# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
25# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
26# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
27# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29# Build the kernel for all targets using the Android build environment.
30#
31# TODO: Accept arguments to indicate what to build.
32
33import glob
34from optparse import OptionParser
35import subprocess
36import os
37import os.path
Andrew Walkerfc0606c2012-10-23 18:43:11 -070038import re
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -070039import shutil
40import sys
41
42version = 'build-all.py, version 0.01'
43
44build_dir = '../all-kernels'
David Brown8e881292012-08-23 11:17:01 -070045make_command = ["vmlinux", "modules", "dtbs"]
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -070046make_env = os.environ
47make_env.update({
48 'ARCH': 'arm',
49 'CROSS_COMPILE': 'arm-none-linux-gnueabi-',
50 'KCONFIG_NOTIMESTAMP': 'true' })
51all_options = {}
52
53def error(msg):
54 sys.stderr.write("error: %s\n" % msg)
55
56def fail(msg):
57 """Fail with a user-printed message"""
58 error(msg)
59 sys.exit(1)
60
61def check_kernel():
62 """Ensure that PWD is a kernel directory"""
63 if (not os.path.isfile('MAINTAINERS') or
64 not os.path.isfile('arch/arm/mach-msm/Kconfig')):
65 fail("This doesn't seem to be an MSM kernel dir")
66
67def check_build():
68 """Ensure that the build directory is present."""
69 if not os.path.isdir(build_dir):
70 try:
71 os.makedirs(build_dir)
72 except OSError as exc:
73 if exc.errno == errno.EEXIST:
74 pass
75 else:
76 raise
77
78def update_config(file, str):
79 print 'Updating %s with \'%s\'\n' % (file, str)
80 defconfig = open(file, 'a')
81 defconfig.write(str + '\n')
82 defconfig.close()
83
84def scan_configs():
85 """Get the full list of defconfigs appropriate for this tree."""
86 names = {}
Andrew Walkerfc0606c2012-10-23 18:43:11 -070087 arch_pats = (
88 r'[fm]sm[0-9]*_defconfig',
89 r'apq*_defconfig',
90 r'qsd*_defconfig',
91 r'omap2*_defconfig',
92 )
93 for p in arch_pats:
94 for n in glob.glob('arch/arm/configs/' + p):
95 names[os.path.basename(n)[:-10]] = n
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -070096 return names
97
98class Builder:
99 def __init__(self, logname):
100 self.logname = logname
101 self.fd = open(logname, 'w')
102
103 def run(self, args):
104 devnull = open('/dev/null', 'r')
105 proc = subprocess.Popen(args, stdin=devnull,
106 env=make_env,
107 bufsize=0,
108 stdout=subprocess.PIPE,
109 stderr=subprocess.STDOUT)
110 count = 0
111 # for line in proc.stdout:
112 rawfd = proc.stdout.fileno()
113 while True:
114 line = os.read(rawfd, 1024)
115 if not line:
116 break
117 self.fd.write(line)
118 self.fd.flush()
119 if all_options.verbose:
120 sys.stdout.write(line)
121 sys.stdout.flush()
122 else:
123 for i in range(line.count('\n')):
124 count += 1
125 if count == 64:
126 count = 0
127 print
128 sys.stdout.write('.')
129 sys.stdout.flush()
130 print
131 result = proc.wait()
132
133 self.fd.close()
134 return result
135
136failed_targets = []
137
138def build(target):
139 dest_dir = os.path.join(build_dir, target)
140 log_name = '%s/log-%s.log' % (build_dir, target)
141 print 'Building %s in %s log %s' % (target, dest_dir, log_name)
142 if not os.path.isdir(dest_dir):
143 os.mkdir(dest_dir)
144 defconfig = 'arch/arm/configs/%s_defconfig' % target
145 dotconfig = '%s/.config' % dest_dir
146 savedefconfig = '%s/defconfig' % dest_dir
147 shutil.copyfile(defconfig, dotconfig)
148
Andrew Walkerfc0606c2012-10-23 18:43:11 -0700149 staging_dir = 'install_staging'
150 modi_dir = '%s' % staging_dir
151 hdri_dir = '%s/usr' % staging_dir
152 shutil.rmtree(os.path.join(dest_dir, staging_dir), ignore_errors=True)
153
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -0700154 devnull = open('/dev/null', 'r')
155 subprocess.check_call(['make', 'O=%s' % dest_dir,
156 '%s_defconfig' % target], env=make_env, stdin=devnull)
157 devnull.close()
158
159 if not all_options.updateconfigs:
Andrew Walkerfc0606c2012-10-23 18:43:11 -0700160 # Build targets can be dependent upon the completion of previous
161 # build targets, so build them one at a time.
162 cmd_line = ['make',
163 'INSTALL_HDR_PATH=%s' % hdri_dir,
164 'INSTALL_MOD_PATH=%s' % modi_dir,
165 'O=%s' % dest_dir]
166 build_targets = []
167 for c in make_command:
168 if re.match(r'^-{1,2}\w', c):
169 cmd_line.append(c)
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -0700170 else:
Andrew Walkerfc0606c2012-10-23 18:43:11 -0700171 build_targets.append(c)
172 for t in build_targets:
173 build = Builder(log_name)
174
175 result = build.run(cmd_line + [t])
176 if result != 0:
177 if all_options.keep_going:
178 failed_targets.append(target)
179 fail_or_error = error
180 else:
181 fail_or_error = fail
182 fail_or_error("Failed to build %s, see %s" %
183 (target, build.logname))
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -0700184
185 # Copy the defconfig back.
186 if all_options.configs or all_options.updateconfigs:
187 devnull = open('/dev/null', 'r')
188 subprocess.check_call(['make', 'O=%s' % dest_dir,
189 'savedefconfig'], env=make_env, stdin=devnull)
190 devnull.close()
191 shutil.copyfile(savedefconfig, defconfig)
192
193def build_many(allconf, targets):
194 print "Building %d target(s)" % len(targets)
195 for target in targets:
196 if all_options.updateconfigs:
197 update_config(allconf[target], all_options.updateconfigs)
198 build(target)
199 if failed_targets:
200 fail('\n '.join(["Failed targets:"] +
201 [target for target in failed_targets]))
202
203def main():
204 global make_command
205
206 check_kernel()
207 check_build()
208
209 configs = scan_configs()
210
211 usage = ("""
212 %prog [options] all -- Build all targets
213 %prog [options] target target ... -- List specific targets
214 %prog [options] perf -- Build all perf targets
215 %prog [options] noperf -- Build all non-perf targets""")
216 parser = OptionParser(usage=usage, version=version)
217 parser.add_option('--configs', action='store_true',
218 dest='configs',
219 help="Copy configs back into tree")
220 parser.add_option('--list', action='store_true',
221 dest='list',
222 help='List available targets')
223 parser.add_option('-v', '--verbose', action='store_true',
224 dest='verbose',
225 help='Output to stdout in addition to log file')
226 parser.add_option('--oldconfig', action='store_true',
227 dest='oldconfig',
228 help='Only process "make oldconfig"')
229 parser.add_option('--updateconfigs',
230 dest='updateconfigs',
231 help="Update defconfigs with provided option setting, "
232 "e.g. --updateconfigs=\'CONFIG_USE_THING=y\'")
233 parser.add_option('-j', '--jobs', type='int', dest="jobs",
234 help="Number of simultaneous jobs")
235 parser.add_option('-l', '--load-average', type='int',
236 dest='load_average',
237 help="Don't start multiple jobs unless load is below LOAD_AVERAGE")
238 parser.add_option('-k', '--keep-going', action='store_true',
239 dest='keep_going', default=False,
240 help="Keep building other targets if a target fails")
241 parser.add_option('-m', '--make-target', action='append',
242 help='Build the indicated make target (default: %s)' %
243 ' '.join(make_command))
244
245 (options, args) = parser.parse_args()
246 global all_options
247 all_options = options
248
249 if options.list:
250 print "Available targets:"
251 for target in configs.keys():
252 print " %s" % target
253 sys.exit(0)
254
255 if options.oldconfig:
256 make_command = ["oldconfig"]
257 elif options.make_target:
258 make_command = options.make_target
259
260 if options.jobs:
261 make_command.append("-j%d" % options.jobs)
262 if options.load_average:
263 make_command.append("-l%d" % options.load_average)
264
265 if args == ['all']:
266 build_many(configs, configs.keys())
267 elif args == ['perf']:
268 targets = []
269 for t in configs.keys():
270 if "perf" in t:
271 targets.append(t)
272 build_many(configs, targets)
273 elif args == ['noperf']:
274 targets = []
275 for t in configs.keys():
276 if "perf" not in t:
277 targets.append(t)
278 build_many(configs, targets)
279 elif len(args) > 0:
280 targets = []
281 for t in args:
282 if t not in configs.keys():
283 parser.error("Target '%s' not one of %s" % (t, configs.keys()))
284 targets.append(t)
285 build_many(configs, targets)
286 else:
287 parser.error("Must specify a target to build, or 'all'")
288
289if __name__ == "__main__":
290 main()