blob: 6135253da64967e45b9fe0a10789fd0a48e1e27e [file] [log] [blame]
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -07001#! /usr/bin/env python
2
3# Copyright (c) 2009-2011, Code Aurora Forum. All rights reserved.
4#
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.
12# * Neither the name of Code Aurora nor
13# 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
38import shutil
39import sys
40
41version = 'build-all.py, version 0.01'
42
43build_dir = '../all-kernels'
44make_command = ["vmlinux", "modules"]
45make_env = os.environ
46make_env.update({
47 'ARCH': 'arm',
48 'CROSS_COMPILE': 'arm-none-linux-gnueabi-',
49 'KCONFIG_NOTIMESTAMP': 'true' })
50all_options = {}
51
52def error(msg):
53 sys.stderr.write("error: %s\n" % msg)
54
55def fail(msg):
56 """Fail with a user-printed message"""
57 error(msg)
58 sys.exit(1)
59
60def check_kernel():
61 """Ensure that PWD is a kernel directory"""
62 if (not os.path.isfile('MAINTAINERS') or
63 not os.path.isfile('arch/arm/mach-msm/Kconfig')):
64 fail("This doesn't seem to be an MSM kernel dir")
65
66def check_build():
67 """Ensure that the build directory is present."""
68 if not os.path.isdir(build_dir):
69 try:
70 os.makedirs(build_dir)
71 except OSError as exc:
72 if exc.errno == errno.EEXIST:
73 pass
74 else:
75 raise
76
77def update_config(file, str):
78 print 'Updating %s with \'%s\'\n' % (file, str)
79 defconfig = open(file, 'a')
80 defconfig.write(str + '\n')
81 defconfig.close()
82
83def scan_configs():
84 """Get the full list of defconfigs appropriate for this tree."""
85 names = {}
86 for n in glob.glob('arch/arm/configs/msm[0-9]*_defconfig'):
87 names[os.path.basename(n)[:-10]] = n
88 for n in glob.glob('arch/arm/configs/qsd*_defconfig'):
89 names[os.path.basename(n)[:-10]] = n
90 return names
91
92class Builder:
93 def __init__(self, logname):
94 self.logname = logname
95 self.fd = open(logname, 'w')
96
97 def run(self, args):
98 devnull = open('/dev/null', 'r')
99 proc = subprocess.Popen(args, stdin=devnull,
100 env=make_env,
101 bufsize=0,
102 stdout=subprocess.PIPE,
103 stderr=subprocess.STDOUT)
104 count = 0
105 # for line in proc.stdout:
106 rawfd = proc.stdout.fileno()
107 while True:
108 line = os.read(rawfd, 1024)
109 if not line:
110 break
111 self.fd.write(line)
112 self.fd.flush()
113 if all_options.verbose:
114 sys.stdout.write(line)
115 sys.stdout.flush()
116 else:
117 for i in range(line.count('\n')):
118 count += 1
119 if count == 64:
120 count = 0
121 print
122 sys.stdout.write('.')
123 sys.stdout.flush()
124 print
125 result = proc.wait()
126
127 self.fd.close()
128 return result
129
130failed_targets = []
131
132def build(target):
133 dest_dir = os.path.join(build_dir, target)
134 log_name = '%s/log-%s.log' % (build_dir, target)
135 print 'Building %s in %s log %s' % (target, dest_dir, log_name)
136 if not os.path.isdir(dest_dir):
137 os.mkdir(dest_dir)
138 defconfig = 'arch/arm/configs/%s_defconfig' % target
139 dotconfig = '%s/.config' % dest_dir
140 savedefconfig = '%s/defconfig' % dest_dir
141 shutil.copyfile(defconfig, dotconfig)
142
143 devnull = open('/dev/null', 'r')
144 subprocess.check_call(['make', 'O=%s' % dest_dir,
145 '%s_defconfig' % target], env=make_env, stdin=devnull)
146 devnull.close()
147
148 if not all_options.updateconfigs:
149 build = Builder(log_name)
150
151 result = build.run(['make', 'O=%s' % dest_dir] + make_command)
152
153 if result != 0:
154 if all_options.keep_going:
155 failed_targets.append(target)
156 fail_or_error = error
157 else:
158 fail_or_error = fail
159 fail_or_error("Failed to build %s, see %s" % (target, build.logname))
160
161 # Copy the defconfig back.
162 if all_options.configs or all_options.updateconfigs:
163 devnull = open('/dev/null', 'r')
164 subprocess.check_call(['make', 'O=%s' % dest_dir,
165 'savedefconfig'], env=make_env, stdin=devnull)
166 devnull.close()
167 shutil.copyfile(savedefconfig, defconfig)
168
169def build_many(allconf, targets):
170 print "Building %d target(s)" % len(targets)
171 for target in targets:
172 if all_options.updateconfigs:
173 update_config(allconf[target], all_options.updateconfigs)
174 build(target)
175 if failed_targets:
176 fail('\n '.join(["Failed targets:"] +
177 [target for target in failed_targets]))
178
179def main():
180 global make_command
181
182 check_kernel()
183 check_build()
184
185 configs = scan_configs()
186
187 usage = ("""
188 %prog [options] all -- Build all targets
189 %prog [options] target target ... -- List specific targets
190 %prog [options] perf -- Build all perf targets
191 %prog [options] noperf -- Build all non-perf targets""")
192 parser = OptionParser(usage=usage, version=version)
193 parser.add_option('--configs', action='store_true',
194 dest='configs',
195 help="Copy configs back into tree")
196 parser.add_option('--list', action='store_true',
197 dest='list',
198 help='List available targets')
199 parser.add_option('-v', '--verbose', action='store_true',
200 dest='verbose',
201 help='Output to stdout in addition to log file')
202 parser.add_option('--oldconfig', action='store_true',
203 dest='oldconfig',
204 help='Only process "make oldconfig"')
205 parser.add_option('--updateconfigs',
206 dest='updateconfigs',
207 help="Update defconfigs with provided option setting, "
208 "e.g. --updateconfigs=\'CONFIG_USE_THING=y\'")
209 parser.add_option('-j', '--jobs', type='int', dest="jobs",
210 help="Number of simultaneous jobs")
211 parser.add_option('-l', '--load-average', type='int',
212 dest='load_average',
213 help="Don't start multiple jobs unless load is below LOAD_AVERAGE")
214 parser.add_option('-k', '--keep-going', action='store_true',
215 dest='keep_going', default=False,
216 help="Keep building other targets if a target fails")
217 parser.add_option('-m', '--make-target', action='append',
218 help='Build the indicated make target (default: %s)' %
219 ' '.join(make_command))
220
221 (options, args) = parser.parse_args()
222 global all_options
223 all_options = options
224
225 if options.list:
226 print "Available targets:"
227 for target in configs.keys():
228 print " %s" % target
229 sys.exit(0)
230
231 if options.oldconfig:
232 make_command = ["oldconfig"]
233 elif options.make_target:
234 make_command = options.make_target
235
236 if options.jobs:
237 make_command.append("-j%d" % options.jobs)
238 if options.load_average:
239 make_command.append("-l%d" % options.load_average)
240
241 if args == ['all']:
242 build_many(configs, configs.keys())
243 elif args == ['perf']:
244 targets = []
245 for t in configs.keys():
246 if "perf" in t:
247 targets.append(t)
248 build_many(configs, targets)
249 elif args == ['noperf']:
250 targets = []
251 for t in configs.keys():
252 if "perf" not in t:
253 targets.append(t)
254 build_many(configs, targets)
255 elif len(args) > 0:
256 targets = []
257 for t in args:
258 if t not in configs.keys():
259 parser.error("Target '%s' not one of %s" % (t, configs.keys()))
260 targets.append(t)
261 build_many(configs, targets)
262 else:
263 parser.error("Must specify a target to build, or 'all'")
264
265if __name__ == "__main__":
266 main()