]> Git Repo - J-u-boot.git/blame - tools/buildman/builderthread.py
tools: kwbimage: Set BOOT_FROM by default to SPI
[J-u-boot.git] / tools / buildman / builderthread.py
CommitLineData
83d290c5 1# SPDX-License-Identifier: GPL-2.0+
190064b4
SG
2# Copyright (c) 2014 Google, Inc
3#
190064b4
SG
4
5import errno
6import glob
7import os
8import shutil
409fc029 9import sys
190064b4
SG
10import threading
11
bf776679
SG
12from patman import command
13from patman import gitutil
190064b4 14
88c8dcf9 15RETURN_CODE_RETRY = -1
73da3d2c 16BASE_ELF_FILENAMES = ['u-boot', 'spl/u-boot-spl', 'tpl/u-boot-tpl']
88c8dcf9 17
f3d015cb 18def Mkdir(dirname, parents = False):
190064b4
SG
19 """Make a directory if it doesn't already exist.
20
21 Args:
22 dirname: Directory to create
23 """
24 try:
f3d015cb
TR
25 if parents:
26 os.makedirs(dirname)
27 else:
28 os.mkdir(dirname)
190064b4
SG
29 except OSError as err:
30 if err.errno == errno.EEXIST:
409fc029 31 if os.path.realpath('.') == os.path.realpath(dirname):
c05aa036 32 print("Cannot create the current working directory '%s'!" % dirname)
409fc029 33 sys.exit(1)
190064b4
SG
34 pass
35 else:
36 raise
37
38class BuilderJob:
39 """Holds information about a job to be performed by a thread
40
41 Members:
42 board: Board object to build
e9fbbf63
SG
43 commits: List of Commit objects to build
44 keep_outputs: True to save build output files
45 step: 1 to process every commit, n to process every nth commit
d829f121
SG
46 work_in_output: Use the output directory as the work directory and
47 don't write to a separate output directory.
190064b4
SG
48 """
49 def __init__(self):
50 self.board = None
51 self.commits = []
e9fbbf63
SG
52 self.keep_outputs = False
53 self.step = 1
d829f121 54 self.work_in_output = False
190064b4
SG
55
56
57class ResultThread(threading.Thread):
58 """This thread processes results from builder threads.
59
60 It simply passes the results on to the builder. There is only one
61 result thread, and this helps to serialise the build output.
62 """
63 def __init__(self, builder):
64 """Set up a new result thread
65
66 Args:
67 builder: Builder which will be sent each result
68 """
69 threading.Thread.__init__(self)
70 self.builder = builder
71
72 def run(self):
73 """Called to start up the result thread.
74
75 We collect the next result job and pass it on to the build.
76 """
77 while True:
78 result = self.builder.out_queue.get()
79 self.builder.ProcessResult(result)
80 self.builder.out_queue.task_done()
81
82
83class BuilderThread(threading.Thread):
84 """This thread builds U-Boot for a particular board.
85
86 An input queue provides each new job. We run 'make' to build U-Boot
87 and then pass the results on to the output queue.
88
89 Members:
90 builder: The builder which contains information we might need
91 thread_num: Our thread number (0-n-1), used to decide on a
24993313
SG
92 temporary directory. If this is -1 then there are no threads
93 and we are the (only) main process
94 mrproper: Use 'make mrproper' before each reconfigure
95 per_board_out_dir: True to build in a separate persistent directory per
96 board rather than a thread-specific directory
97 test_exception: Used for testing; True to raise an exception instead of
98 reporting the build result
190064b4 99 """
8116c78f
SG
100 def __init__(self, builder, thread_num, mrproper, per_board_out_dir,
101 test_exception=False):
190064b4
SG
102 """Set up a new builder thread"""
103 threading.Thread.__init__(self)
104 self.builder = builder
105 self.thread_num = thread_num
eb70a2c0 106 self.mrproper = mrproper
f79f1e0c 107 self.per_board_out_dir = per_board_out_dir
8116c78f 108 self.test_exception = test_exception
190064b4
SG
109
110 def Make(self, commit, brd, stage, cwd, *args, **kwargs):
111 """Run 'make' on a particular commit and board.
112
113 The source code will already be checked out, so the 'commit'
114 argument is only for information.
115
116 Args:
117 commit: Commit object that is being built
118 brd: Board object that is being built
119 stage: Stage of the build. Valid stages are:
fd18a89e 120 mrproper - can be called to clean source
190064b4
SG
121 config - called to configure for a board
122 build - the main make invocation - it does the build
123 args: A list of arguments to pass to 'make'
124 kwargs: A list of keyword arguments to pass to command.RunPipe()
125
126 Returns:
127 CommandResult object
128 """
129 return self.builder.do_make(commit, brd, stage, cwd, *args,
130 **kwargs)
131
a9401b2b 132 def RunCommit(self, commit_upto, brd, work_dir, do_config, config_only,
d829f121 133 force_build, force_build_failures, work_in_output):
190064b4
SG
134 """Build a particular commit.
135
136 If the build is already done, and we are not forcing a build, we skip
137 the build and just return the previously-saved results.
138
139 Args:
140 commit_upto: Commit number to build (0...n-1)
141 brd: Board object to build
142 work_dir: Directory to which the source will be checked out
143 do_config: True to run a make <board>_defconfig on the source
a9401b2b 144 config_only: Only configure the source, do not build it
190064b4
SG
145 force_build: Force a build even if one was previously done
146 force_build_failures: Force a bulid if the previous result showed
147 failure
d829f121
SG
148 work_in_output: Use the output directory as the work directory and
149 don't write to a separate output directory.
190064b4
SG
150
151 Returns:
152 tuple containing:
153 - CommandResult object containing the results of the build
154 - boolean indicating whether 'make config' is still needed
155 """
156 # Create a default result - it will be overwritte by the call to
157 # self.Make() below, in the event that we do a build.
158 result = command.CommandResult()
159 result.return_code = 0
d829f121 160 if work_in_output or self.builder.in_tree:
190064b4
SG
161 out_dir = work_dir
162 else:
f79f1e0c
SW
163 if self.per_board_out_dir:
164 out_rel_dir = os.path.join('..', brd.target)
165 else:
166 out_rel_dir = 'build'
167 out_dir = os.path.join(work_dir, out_rel_dir)
190064b4
SG
168
169 # Check if the job was already completed last time
170 done_file = self.builder.GetDoneFile(commit_upto, brd.target)
171 result.already_done = os.path.exists(done_file)
172 will_build = (force_build or force_build_failures or
173 not result.already_done)
fb3954f9 174 if result.already_done:
190064b4
SG
175 # Get the return code from that build and use it
176 with open(done_file, 'r') as fd:
e74429bb
SG
177 try:
178 result.return_code = int(fd.readline())
179 except ValueError:
180 # The file may be empty due to running out of disk space.
181 # Try a rebuild
182 result.return_code = RETURN_CODE_RETRY
88c8dcf9
SG
183
184 # Check the signal that the build needs to be retried
185 if result.return_code == RETURN_CODE_RETRY:
186 will_build = True
187 elif will_build:
fb3954f9
SG
188 err_file = self.builder.GetErrFile(commit_upto, brd.target)
189 if os.path.exists(err_file) and os.stat(err_file).st_size:
190 result.stderr = 'bad'
191 elif not force_build:
192 # The build passed, so no need to build it again
193 will_build = False
190064b4
SG
194
195 if will_build:
196 # We are going to have to build it. First, get a toolchain
197 if not self.toolchain:
198 try:
199 self.toolchain = self.builder.toolchains.Select(brd.arch)
200 except ValueError as err:
201 result.return_code = 10
202 result.stdout = ''
203 result.stderr = str(err)
204 # TODO([email protected]): This gets swallowed, but needs
205 # to be reported.
206
207 if self.toolchain:
208 # Checkout the right commit
209 if self.builder.commits:
210 commit = self.builder.commits[commit_upto]
211 if self.builder.checkout:
212 git_dir = os.path.join(work_dir, '.git')
213 gitutil.Checkout(commit.hash, git_dir, work_dir,
214 force=True)
215 else:
216 commit = 'current'
217
218 # Set up the environment and command line
bb1501f2 219 env = self.toolchain.MakeEnvironment(self.builder.full_path)
190064b4
SG
220 Mkdir(out_dir)
221 args = []
222 cwd = work_dir
48c1b6a8 223 src_dir = os.path.realpath(work_dir)
190064b4
SG
224 if not self.builder.in_tree:
225 if commit_upto is None:
226 # In this case we are building in the original source
227 # directory (i.e. the current directory where buildman
228 # is invoked. The output directory is set to this
229 # thread's selected work directory.
230 #
231 # Symlinks can confuse U-Boot's Makefile since
232 # we may use '..' in our path, so remove them.
f79f1e0c
SW
233 out_dir = os.path.realpath(out_dir)
234 args.append('O=%s' % out_dir)
190064b4 235 cwd = None
48c1b6a8 236 src_dir = os.getcwd()
190064b4 237 else:
f79f1e0c 238 args.append('O=%s' % out_rel_dir)
f5e5ece0
TR
239 if self.builder.verbose_build:
240 args.append('V=1')
241 else:
d2ce658d 242 args.append('-s')
190064b4
SG
243 if self.builder.num_jobs is not None:
244 args.extend(['-j', str(self.builder.num_jobs)])
2371d1bc
DS
245 if self.builder.warnings_as_errors:
246 args.append('KCFLAGS=-Werror')
190064b4
SG
247 config_args = ['%s_defconfig' % brd.target]
248 config_out = ''
249 args.extend(self.builder.toolchains.GetMakeArguments(brd))
00beb248 250 args.extend(self.toolchain.MakeArgs())
190064b4 251
73da3d2c
SG
252 # Remove any output targets. Since we use a build directory that
253 # was previously used by another board, it may have produced an
254 # SPL image. If we don't remove it (i.e. see do_config and
255 # self.mrproper below) then it will appear to be the output of
256 # this build, even if it does not produce SPL images.
257 build_dir = self.builder.GetBuildDir(commit_upto, brd.target)
258 for elf in BASE_ELF_FILENAMES:
259 fname = os.path.join(out_dir, elf)
260 if os.path.exists(fname):
261 os.remove(fname)
262
190064b4
SG
263 # If we need to reconfigure, do that now
264 if do_config:
f79f1e0c 265 config_out = ''
eb70a2c0 266 if self.mrproper:
f79f1e0c
SW
267 result = self.Make(commit, brd, 'mrproper', cwd,
268 'mrproper', *args, env=env)
269 config_out += result.combined
190064b4
SG
270 result = self.Make(commit, brd, 'config', cwd,
271 *(args + config_args), env=env)
40f11fce 272 config_out += result.combined
190064b4
SG
273 do_config = False # No need to configure next time
274 if result.return_code == 0:
a9401b2b 275 if config_only:
b50113f3 276 args.append('cfg')
190064b4
SG
277 result = self.Make(commit, brd, 'build', cwd, *args,
278 env=env)
48c1b6a8 279 result.stderr = result.stderr.replace(src_dir + '/', '')
40f11fce
SG
280 if self.builder.verbose_build:
281 result.stdout = config_out + result.stdout
190064b4
SG
282 else:
283 result.return_code = 1
284 result.stderr = 'No tool chain for %s\n' % brd.arch
285 result.already_done = False
286
287 result.toolchain = self.toolchain
288 result.brd = brd
289 result.commit_upto = commit_upto
290 result.out_dir = out_dir
291 return result, do_config
292
d829f121 293 def _WriteResult(self, result, keep_outputs, work_in_output):
190064b4
SG
294 """Write a built result to the output directory.
295
296 Args:
297 result: CommandResult object containing result to write
298 keep_outputs: True to store the output binaries, False
299 to delete them
d829f121
SG
300 work_in_output: Use the output directory as the work directory and
301 don't write to a separate output directory.
190064b4 302 """
88c8dcf9
SG
303 # If we think this might have been aborted with Ctrl-C, record the
304 # failure but not that we are 'done' with this board. A retry may fix
305 # it.
bafdeb45 306 maybe_aborted = result.stderr and 'No child processes' in result.stderr
190064b4 307
bafdeb45 308 if result.return_code >= 0 and result.already_done:
190064b4
SG
309 return
310
311 # Write the output and stderr
312 output_dir = self.builder._GetOutputDir(result.commit_upto)
313 Mkdir(output_dir)
314 build_dir = self.builder.GetBuildDir(result.commit_upto,
315 result.brd.target)
316 Mkdir(build_dir)
317
318 outfile = os.path.join(build_dir, 'log')
319 with open(outfile, 'w') as fd:
320 if result.stdout:
c05aa036 321 fd.write(result.stdout)
190064b4
SG
322
323 errfile = self.builder.GetErrFile(result.commit_upto,
324 result.brd.target)
325 if result.stderr:
326 with open(errfile, 'w') as fd:
c05aa036 327 fd.write(result.stderr)
190064b4
SG
328 elif os.path.exists(errfile):
329 os.remove(errfile)
330
bafdeb45
SG
331 # Fatal error
332 if result.return_code < 0:
333 return
334
190064b4
SG
335 if result.toolchain:
336 # Write the build result and toolchain information.
337 done_file = self.builder.GetDoneFile(result.commit_upto,
338 result.brd.target)
339 with open(done_file, 'w') as fd:
88c8dcf9
SG
340 if maybe_aborted:
341 # Special code to indicate we need to retry
342 fd.write('%s' % RETURN_CODE_RETRY)
343 else:
344 fd.write('%s' % result.return_code)
190064b4 345 with open(os.path.join(build_dir, 'toolchain'), 'w') as fd:
c05aa036
SG
346 print('gcc', result.toolchain.gcc, file=fd)
347 print('path', result.toolchain.path, file=fd)
348 print('cross', result.toolchain.cross, file=fd)
349 print('arch', result.toolchain.arch, file=fd)
190064b4
SG
350 fd.write('%s' % result.return_code)
351
190064b4 352 # Write out the image and function size information and an objdump
bb1501f2 353 env = result.toolchain.MakeEnvironment(self.builder.full_path)
f1a83abe 354 with open(os.path.join(build_dir, 'out-env'), 'wb') as fd:
e5fc79ea 355 for var in sorted(env.keys()):
f1a83abe 356 fd.write(b'%s="%s"' % (var, env[var]))
190064b4 357 lines = []
73da3d2c 358 for fname in BASE_ELF_FILENAMES:
190064b4
SG
359 cmd = ['%snm' % self.toolchain.cross, '--size-sort', fname]
360 nm_result = command.RunPipe([cmd], capture=True,
361 capture_stderr=True, cwd=result.out_dir,
362 raise_on_error=False, env=env)
363 if nm_result.stdout:
364 nm = self.builder.GetFuncSizesFile(result.commit_upto,
365 result.brd.target, fname)
366 with open(nm, 'w') as fd:
c05aa036 367 print(nm_result.stdout, end=' ', file=fd)
190064b4
SG
368
369 cmd = ['%sobjdump' % self.toolchain.cross, '-h', fname]
370 dump_result = command.RunPipe([cmd], capture=True,
371 capture_stderr=True, cwd=result.out_dir,
372 raise_on_error=False, env=env)
373 rodata_size = ''
374 if dump_result.stdout:
375 objdump = self.builder.GetObjdumpFile(result.commit_upto,
376 result.brd.target, fname)
377 with open(objdump, 'w') as fd:
c05aa036 378 print(dump_result.stdout, end=' ', file=fd)
190064b4
SG
379 for line in dump_result.stdout.splitlines():
380 fields = line.split()
381 if len(fields) > 5 and fields[1] == '.rodata':
382 rodata_size = fields[2]
383
384 cmd = ['%ssize' % self.toolchain.cross, fname]
385 size_result = command.RunPipe([cmd], capture=True,
386 capture_stderr=True, cwd=result.out_dir,
387 raise_on_error=False, env=env)
388 if size_result.stdout:
389 lines.append(size_result.stdout.splitlines()[1] + ' ' +
390 rodata_size)
391
0ddc510e
AK
392 # Extract the environment from U-Boot and dump it out
393 cmd = ['%sobjcopy' % self.toolchain.cross, '-O', 'binary',
394 '-j', '.rodata.default_environment',
395 'env/built-in.o', 'uboot.env']
396 command.RunPipe([cmd], capture=True,
397 capture_stderr=True, cwd=result.out_dir,
398 raise_on_error=False, env=env)
399 ubootenv = os.path.join(result.out_dir, 'uboot.env')
60b285f8
SG
400 if not work_in_output:
401 self.CopyFiles(result.out_dir, build_dir, '', ['uboot.env'])
0ddc510e 402
190064b4
SG
403 # Write out the image sizes file. This is similar to the output
404 # of binutil's 'size' utility, but it omits the header line and
405 # adds an additional hex value at the end of each line for the
406 # rodata size
407 if len(lines):
408 sizes = self.builder.GetSizesFile(result.commit_upto,
409 result.brd.target)
410 with open(sizes, 'w') as fd:
c05aa036 411 print('\n'.join(lines), file=fd)
190064b4 412
60b285f8
SG
413 if not work_in_output:
414 # Write out the configuration files, with a special case for SPL
415 for dirname in ['', 'spl', 'tpl']:
416 self.CopyFiles(
417 result.out_dir, build_dir, dirname,
418 ['u-boot.cfg', 'spl/u-boot-spl.cfg', 'tpl/u-boot-tpl.cfg',
419 '.config', 'include/autoconf.mk',
420 'include/generated/autoconf.h'])
421
422 # Now write the actual build output
423 if keep_outputs:
424 self.CopyFiles(
425 result.out_dir, build_dir, '',
426 ['u-boot*', '*.bin', '*.map', '*.img', 'MLO', 'SPL',
427 'include/autoconf.mk', 'spl/u-boot-spl*'])
970f932a
SG
428
429 def CopyFiles(self, out_dir, build_dir, dirname, patterns):
430 """Copy files from the build directory to the output.
190064b4 431
970f932a
SG
432 Args:
433 out_dir: Path to output directory containing the files
434 build_dir: Place to copy the files
435 dirname: Source directory, '' for normal U-Boot, 'spl' for SPL
436 patterns: A list of filenames (strings) to copy, each relative
437 to the build directory
438 """
439 for pattern in patterns:
440 file_list = glob.glob(os.path.join(out_dir, dirname, pattern))
441 for fname in file_list:
442 target = os.path.basename(fname)
443 if dirname:
444 base, ext = os.path.splitext(target)
445 if ext:
446 target = '%s-%s%s' % (base, dirname, ext)
447 shutil.copy(fname, os.path.join(build_dir, target))
190064b4 448
ab9b4f35
SG
449 def _SendResult(self, result):
450 """Send a result to the builder for processing
451
452 Args:
453 result: CommandResult object containing the results of the build
8116c78f
SG
454
455 Raises:
456 ValueError if self.test_exception is true (for testing)
ab9b4f35 457 """
8116c78f
SG
458 if self.test_exception:
459 raise ValueError('test exception')
ab9b4f35
SG
460 if self.thread_num != -1:
461 self.builder.out_queue.put(result)
462 else:
463 self.builder.ProcessResult(result)
464
190064b4
SG
465 def RunJob(self, job):
466 """Run a single job
467
468 A job consists of a building a list of commits for a particular board.
469
470 Args:
471 job: Job to build
b82492bb
SG
472
473 Returns:
474 List of Result objects
190064b4
SG
475 """
476 brd = job.board
477 work_dir = self.builder.GetThreadDir(self.thread_num)
478 self.toolchain = None
479 if job.commits:
480 # Run 'make board_defconfig' on the first commit
481 do_config = True
482 commit_upto = 0
483 force_build = False
484 for commit_upto in range(0, len(job.commits), job.step):
485 result, request_config = self.RunCommit(commit_upto, brd,
a9401b2b 486 work_dir, do_config, self.builder.config_only,
190064b4 487 force_build or self.builder.force_build,
d829f121
SG
488 self.builder.force_build_failures,
489 work_in_output=job.work_in_output)
190064b4
SG
490 failed = result.return_code or result.stderr
491 did_config = do_config
492 if failed and not do_config:
493 # If our incremental build failed, try building again
494 # with a reconfig.
495 if self.builder.force_config_on_failure:
496 result, request_config = self.RunCommit(commit_upto,
d829f121
SG
497 brd, work_dir, True, False, True, False,
498 work_in_output=job.work_in_output)
190064b4
SG
499 did_config = True
500 if not self.builder.force_reconfig:
501 do_config = request_config
502
503 # If we built that commit, then config is done. But if we got
504 # an warning, reconfig next time to force it to build the same
505 # files that created warnings this time. Otherwise an
506 # incremental build may not build the same file, and we will
507 # think that the warning has gone away.
508 # We could avoid this by using -Werror everywhere...
509 # For errors, the problem doesn't happen, since presumably
510 # the build stopped and didn't generate output, so will retry
511 # that file next time. So we could detect warnings and deal
512 # with them specially here. For now, we just reconfigure if
513 # anything goes work.
514 # Of course this is substantially slower if there are build
515 # errors/warnings (e.g. 2-3x slower even if only 10% of builds
516 # have problems).
517 if (failed and not result.already_done and not did_config and
518 self.builder.force_config_on_failure):
519 # If this build failed, try the next one with a
520 # reconfigure.
521 # Sometimes if the board_config.h file changes it can mess
522 # with dependencies, and we get:
523 # make: *** No rule to make target `include/autoconf.mk',
524 # needed by `depend'.
525 do_config = True
526 force_build = True
527 else:
528 force_build = False
529 if self.builder.force_config_on_failure:
530 if failed:
531 do_config = True
532 result.commit_upto = commit_upto
533 if result.return_code < 0:
534 raise ValueError('Interrupt')
535
536 # We have the build results, so output the result
d829f121 537 self._WriteResult(result, job.keep_outputs, job.work_in_output)
ab9b4f35 538 self._SendResult(result)
190064b4
SG
539 else:
540 # Just build the currently checked-out build
541 result, request_config = self.RunCommit(None, brd, work_dir, True,
a9401b2b 542 self.builder.config_only, True,
d829f121
SG
543 self.builder.force_build_failures,
544 work_in_output=job.work_in_output)
190064b4 545 result.commit_upto = 0
d829f121 546 self._WriteResult(result, job.keep_outputs, job.work_in_output)
ab9b4f35 547 self._SendResult(result)
190064b4
SG
548
549 def run(self):
550 """Our thread's run function
551
552 This thread picks a job from the queue, runs it, and then goes to the
553 next job.
554 """
190064b4
SG
555 while True:
556 job = self.builder.queue.get()
8116c78f
SG
557 try:
558 self.RunJob(job)
559 except Exception as e:
560 print('Thread exception:', e)
561 self.builder.thread_exceptions.append(e)
190064b4 562 self.builder.queue.task_done()
This page took 0.426493 seconds and 4 git commands to generate.