build-all.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. #! /usr/bin/env python2
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. # Copyright (c) 2009-2015, 2017-19, The Linux Foundation. All rights reserved.
  4. # Build the kernel for all targets using the Android build environment.
  5. from collections import namedtuple
  6. import glob
  7. from optparse import OptionParser
  8. import os
  9. import re
  10. import shutil
  11. import subprocess
  12. import sys
  13. import threading
  14. import Queue
  15. version = 'build-all.py, version 1.99'
  16. build_dir = '../all-kernels'
  17. make_command = ["vmlinux", "modules", "dtbs"]
  18. all_options = {}
  19. compile64 = os.environ.get('CROSS_COMPILE64')
  20. clang_bin = os.environ.get('CLANG_BIN')
  21. def error(msg):
  22. sys.stderr.write("error: %s\n" % msg)
  23. def fail(msg):
  24. """Fail with a user-printed message"""
  25. error(msg)
  26. sys.exit(1)
  27. if not os.environ.get('CROSS_COMPILE'):
  28. fail("CROSS_COMPILE must be set in the environment")
  29. def check_kernel():
  30. """Ensure that PWD is a kernel directory"""
  31. if not os.path.isfile('MAINTAINERS'):
  32. fail("This doesn't seem to be a kernel dir")
  33. def check_build():
  34. """Ensure that the build directory is present."""
  35. if not os.path.isdir(build_dir):
  36. try:
  37. os.makedirs(build_dir)
  38. except OSError as exc:
  39. if exc.errno == errno.EEXIST:
  40. pass
  41. else:
  42. raise
  43. failed_targets = []
  44. BuildResult = namedtuple('BuildResult', ['status', 'messages'])
  45. class BuildSequence(namedtuple('BuildSequence', ['log_name', 'short_name', 'steps'])):
  46. def set_width(self, width):
  47. self.width = width
  48. def __enter__(self):
  49. self.log = open(self.log_name, 'w')
  50. def __exit__(self, type, value, traceback):
  51. self.log.close()
  52. def run(self):
  53. self.status = None
  54. messages = ["Building: " + self.short_name]
  55. def printer(line):
  56. text = "[%-*s] %s" % (self.width, self.short_name, line)
  57. messages.append(text)
  58. self.log.write(text)
  59. self.log.write('\n')
  60. for step in self.steps:
  61. st = step.run(printer)
  62. if st:
  63. self.status = BuildResult(self.short_name, messages)
  64. break
  65. if not self.status:
  66. self.status = BuildResult(None, messages)
  67. class BuildTracker:
  68. """Manages all of the steps necessary to perform a build. The
  69. build consists of one or more sequences of steps. The different
  70. sequences can be processed independently, while the steps within a
  71. sequence must be done in order."""
  72. def __init__(self, parallel_builds):
  73. self.sequence = []
  74. self.lock = threading.Lock()
  75. self.parallel_builds = parallel_builds
  76. def add_sequence(self, log_name, short_name, steps):
  77. self.sequence.append(BuildSequence(log_name, short_name, steps))
  78. def longest_name(self):
  79. longest = 0
  80. for seq in self.sequence:
  81. longest = max(longest, len(seq.short_name))
  82. return longest
  83. def __repr__(self):
  84. return "BuildTracker(%s)" % self.sequence
  85. def run_child(self, seq):
  86. seq.set_width(self.longest)
  87. tok = self.build_tokens.get()
  88. with self.lock:
  89. print "Building:", seq.short_name
  90. with seq:
  91. seq.run()
  92. self.results.put(seq.status)
  93. self.build_tokens.put(tok)
  94. def run(self):
  95. self.longest = self.longest_name()
  96. self.results = Queue.Queue()
  97. children = []
  98. errors = []
  99. self.build_tokens = Queue.Queue()
  100. nthreads = self.parallel_builds
  101. print "Building with", nthreads, "threads"
  102. for i in range(nthreads):
  103. self.build_tokens.put(True)
  104. for seq in self.sequence:
  105. child = threading.Thread(target=self.run_child, args=[seq])
  106. children.append(child)
  107. child.start()
  108. for child in children:
  109. stats = self.results.get()
  110. if all_options.verbose:
  111. with self.lock:
  112. for line in stats.messages:
  113. print line
  114. sys.stdout.flush()
  115. if stats.status:
  116. errors.append(stats.status)
  117. for child in children:
  118. child.join()
  119. if errors:
  120. fail("\n ".join(["Failed targets:"] + errors))
  121. class PrintStep:
  122. """A step that just prints a message"""
  123. def __init__(self, message):
  124. self.message = message
  125. def run(self, outp):
  126. outp(self.message)
  127. class MkdirStep:
  128. """A step that makes a directory"""
  129. def __init__(self, direc):
  130. self.direc = direc
  131. def run(self, outp):
  132. outp("mkdir %s" % self.direc)
  133. os.mkdir(self.direc)
  134. class RmtreeStep:
  135. def __init__(self, direc):
  136. self.direc = direc
  137. def run(self, outp):
  138. outp("rmtree %s" % self.direc)
  139. shutil.rmtree(self.direc, ignore_errors=True)
  140. class CopyfileStep:
  141. def __init__(self, src, dest):
  142. self.src = src
  143. self.dest = dest
  144. def run(self, outp):
  145. outp("cp %s %s" % (self.src, self.dest))
  146. shutil.copyfile(self.src, self.dest)
  147. class ExecStep:
  148. def __init__(self, cmd, **kwargs):
  149. self.cmd = cmd
  150. self.kwargs = kwargs
  151. def run(self, outp):
  152. outp("exec: %s" % (" ".join(self.cmd),))
  153. with open('/dev/null', 'r') as devnull:
  154. proc = subprocess.Popen(self.cmd, stdin=devnull,
  155. stdout=subprocess.PIPE,
  156. stderr=subprocess.STDOUT,
  157. **self.kwargs)
  158. stdout = proc.stdout
  159. while True:
  160. line = stdout.readline()
  161. if not line:
  162. break
  163. line = line.rstrip('\n')
  164. outp(line)
  165. result = proc.wait()
  166. if result != 0:
  167. return ('error', result)
  168. else:
  169. return None
  170. class Builder():
  171. def __init__(self, name, defconfig):
  172. self.name = name
  173. self.defconfig = defconfig
  174. self.confname = re.sub('arch/arm[64]*/configs/', '', self.defconfig)
  175. # Determine if this is a 64-bit target based on the location
  176. # of the defconfig.
  177. self.make_env = os.environ.copy()
  178. if "/arm64/" in defconfig:
  179. if compile64:
  180. self.make_env['CROSS_COMPILE'] = compile64
  181. else:
  182. fail("Attempting to build 64-bit, without setting CROSS_COMPILE64")
  183. self.make_env['ARCH'] = 'arm64'
  184. else:
  185. self.make_env['ARCH'] = 'arm'
  186. self.make_env['KCONFIG_NOTIMESTAMP'] = 'true'
  187. self.log_name = "%s/log-%s.log" % (build_dir, self.name)
  188. def build(self):
  189. steps = []
  190. dest_dir = os.path.join(build_dir, self.name)
  191. log_name = "%s/log-%s.log" % (build_dir, self.name)
  192. steps.append(PrintStep('Building %s in %s log %s' %
  193. (self.name, dest_dir, log_name)))
  194. if not os.path.isdir(dest_dir):
  195. steps.append(MkdirStep(dest_dir))
  196. defconfig = self.defconfig
  197. dotconfig = '%s/.config' % dest_dir
  198. savedefconfig = '%s/defconfig' % dest_dir
  199. staging_dir = 'install_staging'
  200. modi_dir = '%s' % staging_dir
  201. hdri_dir = '%s/usr' % staging_dir
  202. steps.append(RmtreeStep(os.path.join(dest_dir, staging_dir)))
  203. steps.append(ExecStep(['make', 'O=%s' % dest_dir,
  204. self.confname], env=self.make_env))
  205. # Build targets can be dependent upon the completion of
  206. # previous build targets, so build them one at a time.
  207. cmd_line = ['make',
  208. 'INSTALL_HDR_PATH=%s' % hdri_dir,
  209. 'INSTALL_MOD_PATH=%s' % modi_dir,
  210. 'O=%s' % dest_dir,
  211. 'REAL_CC=%s' % clang_bin]
  212. build_targets = []
  213. for c in make_command:
  214. if re.match(r'^-{1,2}\w', c):
  215. cmd_line.append(c)
  216. else:
  217. build_targets.append(c)
  218. for t in build_targets:
  219. steps.append(ExecStep(cmd_line + [t], env=self.make_env))
  220. return steps
  221. def scan_configs():
  222. """
  223. Get the full list of defconfigs appropriate for this tree,
  224. except for gki_defconfig.
  225. """
  226. names = []
  227. for defconfig in glob.glob('arch/arm*/configs/vendor/*_defconfig'):
  228. target = os.path.basename(defconfig)[:-10]
  229. if 'gki' == target:
  230. continue
  231. name = target + "-llvm"
  232. if 'arch/arm64' in defconfig:
  233. name = name + "-64"
  234. names.append(Builder(name, defconfig))
  235. return names
  236. def build_many(targets):
  237. print "Building %d target(s)" % len(targets)
  238. # To try and make up for the link phase being serial, try to do
  239. # two full builds in parallel. Don't do too many because lots of
  240. # parallel builds tends to use up available memory rather quickly.
  241. parallel = 2
  242. if all_options.jobs and all_options.jobs > 1:
  243. j = max(all_options.jobs / parallel, 2)
  244. make_command.append("-j" + str(j))
  245. tracker = BuildTracker(parallel)
  246. for target in targets:
  247. steps = target.build()
  248. tracker.add_sequence(target.log_name, target.name, steps)
  249. tracker.run()
  250. def main():
  251. global make_command
  252. check_kernel()
  253. check_build()
  254. configs = scan_configs()
  255. usage = ("""
  256. %prog [options] all -- Build all targets
  257. %prog [options] target target ... -- List specific targets
  258. """)
  259. parser = OptionParser(usage=usage, version=version)
  260. parser.add_option('--list', action='store_true',
  261. dest='list',
  262. help='List available targets')
  263. parser.add_option('-v', '--verbose', action='store_true',
  264. dest='verbose',
  265. help='Output to stdout in addition to log file')
  266. parser.add_option('-j', '--jobs', type='int', dest="jobs",
  267. help="Number of simultaneous jobs")
  268. parser.add_option('-l', '--load-average', type='int',
  269. dest='load_average',
  270. help="Don't start multiple jobs unless load is below LOAD_AVERAGE")
  271. parser.add_option('-k', '--keep-going', action='store_true',
  272. dest='keep_going', default=False,
  273. help="Keep building other targets if a target fails")
  274. parser.add_option('-m', '--make-target', action='append',
  275. help='Build the indicated make target (default: %s)' %
  276. ' '.join(make_command))
  277. (options, args) = parser.parse_args()
  278. global all_options
  279. all_options = options
  280. if options.list:
  281. print "Available targets:"
  282. for target in configs:
  283. print " %s" % target.name
  284. sys.exit(0)
  285. if options.make_target:
  286. make_command = options.make_target
  287. if args == ['all']:
  288. build_many(configs)
  289. elif len(args) > 0:
  290. all_configs = {}
  291. for t in configs:
  292. all_configs[t.name] = t
  293. targets = []
  294. for t in args:
  295. if t not in all_configs:
  296. parser.error("Target '%s' not one of %s" % (t, all_configs.keys()))
  297. targets.append(all_configs[t])
  298. build_many(targets)
  299. else:
  300. parser.error("Must specify a target to build, or 'all'")
  301. if __name__ == "__main__":
  302. main()