blob: 296d9adf9414a1fbb97d7095820f8b3cb99ce099 [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 = {}
David Brown2ab0a60d2011-12-14 09:57:36 -080086 for n in glob.glob('arch/arm/configs/[fm]sm[0-9-]*_defconfig'):
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -070087 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
Stephen Boyd9daf9342011-08-02 20:31:00 -070090 for n in glob.glob('arch/arm/configs/apq*_defconfig'):
91 names[os.path.basename(n)[:-10]] = n
Bryan Huntsman3f2bc4d2011-08-16 17:27:22 -070092 return names
93
94class Builder:
95 def __init__(self, logname):
96 self.logname = logname
97 self.fd = open(logname, 'w')
98
99 def run(self, args):
100 devnull = open('/dev/null', 'r')
101 proc = subprocess.Popen(args, stdin=devnull,
102 env=make_env,
103 bufsize=0,
104 stdout=subprocess.PIPE,
105 stderr=subprocess.STDOUT)
106 count = 0
107 # for line in proc.stdout:
108 rawfd = proc.stdout.fileno()
109 while True:
110 line = os.read(rawfd, 1024)
111 if not line:
112 break
113 self.fd.write(line)
114 self.fd.flush()
115 if all_options.verbose:
116 sys.stdout.write(line)
117 sys.stdout.flush()
118 else:
119 for i in range(line.count('\n')):
120 count += 1
121 if count == 64:
122 count = 0
123 print
124 sys.stdout.write('.')
125 sys.stdout.flush()
126 print
127 result = proc.wait()
128
129 self.fd.close()
130 return result
131
132failed_targets = []
133
134def build(target):
135 dest_dir = os.path.join(build_dir, target)
136 log_name = '%s/log-%s.log' % (build_dir, target)
137 print 'Building %s in %s log %s' % (target, dest_dir, log_name)
138 if not os.path.isdir(dest_dir):
139 os.mkdir(dest_dir)
140 defconfig = 'arch/arm/configs/%s_defconfig' % target
141 dotconfig = '%s/.config' % dest_dir
142 savedefconfig = '%s/defconfig' % dest_dir
143 shutil.copyfile(defconfig, dotconfig)
144
145 devnull = open('/dev/null', 'r')
146 subprocess.check_call(['make', 'O=%s' % dest_dir,
147 '%s_defconfig' % target], env=make_env, stdin=devnull)
148 devnull.close()
149
150 if not all_options.updateconfigs:
151 build = Builder(log_name)
152
153 result = build.run(['make', 'O=%s' % dest_dir] + make_command)
154
155 if result != 0:
156 if all_options.keep_going:
157 failed_targets.append(target)
158 fail_or_error = error
159 else:
160 fail_or_error = fail
161 fail_or_error("Failed to build %s, see %s" % (target, build.logname))
162
163 # Copy the defconfig back.
164 if all_options.configs or all_options.updateconfigs:
165 devnull = open('/dev/null', 'r')
166 subprocess.check_call(['make', 'O=%s' % dest_dir,
167 'savedefconfig'], env=make_env, stdin=devnull)
168 devnull.close()
169 shutil.copyfile(savedefconfig, defconfig)
170
171def build_many(allconf, targets):
172 print "Building %d target(s)" % len(targets)
173 for target in targets:
174 if all_options.updateconfigs:
175 update_config(allconf[target], all_options.updateconfigs)
176 build(target)
177 if failed_targets:
178 fail('\n '.join(["Failed targets:"] +
179 [target for target in failed_targets]))
180
181def main():
182 global make_command
183
184 check_kernel()
185 check_build()
186
187 configs = scan_configs()
188
189 usage = ("""
190 %prog [options] all -- Build all targets
191 %prog [options] target target ... -- List specific targets
192 %prog [options] perf -- Build all perf targets
193 %prog [options] noperf -- Build all non-perf targets""")
194 parser = OptionParser(usage=usage, version=version)
195 parser.add_option('--configs', action='store_true',
196 dest='configs',
197 help="Copy configs back into tree")
198 parser.add_option('--list', action='store_true',
199 dest='list',
200 help='List available targets')
201 parser.add_option('-v', '--verbose', action='store_true',
202 dest='verbose',
203 help='Output to stdout in addition to log file')
204 parser.add_option('--oldconfig', action='store_true',
205 dest='oldconfig',
206 help='Only process "make oldconfig"')
207 parser.add_option('--updateconfigs',
208 dest='updateconfigs',
209 help="Update defconfigs with provided option setting, "
210 "e.g. --updateconfigs=\'CONFIG_USE_THING=y\'")
211 parser.add_option('-j', '--jobs', type='int', dest="jobs",
212 help="Number of simultaneous jobs")
213 parser.add_option('-l', '--load-average', type='int',
214 dest='load_average',
215 help="Don't start multiple jobs unless load is below LOAD_AVERAGE")
216 parser.add_option('-k', '--keep-going', action='store_true',
217 dest='keep_going', default=False,
218 help="Keep building other targets if a target fails")
219 parser.add_option('-m', '--make-target', action='append',
220 help='Build the indicated make target (default: %s)' %
221 ' '.join(make_command))
222
223 (options, args) = parser.parse_args()
224 global all_options
225 all_options = options
226
227 if options.list:
228 print "Available targets:"
229 for target in configs.keys():
230 print " %s" % target
231 sys.exit(0)
232
233 if options.oldconfig:
234 make_command = ["oldconfig"]
235 elif options.make_target:
236 make_command = options.make_target
237
238 if options.jobs:
239 make_command.append("-j%d" % options.jobs)
240 if options.load_average:
241 make_command.append("-l%d" % options.load_average)
242
243 if args == ['all']:
244 build_many(configs, configs.keys())
245 elif args == ['perf']:
246 targets = []
247 for t in configs.keys():
248 if "perf" in t:
249 targets.append(t)
250 build_many(configs, targets)
251 elif args == ['noperf']:
252 targets = []
253 for t in configs.keys():
254 if "perf" not in t:
255 targets.append(t)
256 build_many(configs, targets)
257 elif len(args) > 0:
258 targets = []
259 for t in args:
260 if t not in configs.keys():
261 parser.error("Target '%s' not one of %s" % (t, configs.keys()))
262 targets.append(t)
263 build_many(configs, targets)
264 else:
265 parser.error("Must specify a target to build, or 'all'")
266
267if __name__ == "__main__":
268 main()