1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2014 Google, Inc
5 """Implementation the bulider threads
7 This module provides the BuilderThread class, which handles calling the builder
8 based on the jobs provided.
18 from buildman import cfgutil
19 from patman import gitutil
20 from u_boot_pylib import command
22 RETURN_CODE_RETRY = -1
23 BASE_ELF_FILENAMES = ['u-boot', 'spl/u-boot-spl', 'tpl/u-boot-tpl']
25 def mkdir(dirname, parents = False):
26 """Make a directory if it doesn't already exist.
29 dirname: Directory to create
36 except OSError as err:
37 if err.errno == errno.EEXIST:
38 if os.path.realpath('.') == os.path.realpath(dirname):
39 print(f"Cannot create the current working directory '{dirname}'!")
44 # pylint: disable=R0903
46 """Holds information about a job to be performed by a thread
49 brd: Board object to build
50 commits: List of Commit objects to build
51 keep_outputs: True to save build output files
52 step: 1 to process every commit, n to process every nth commit
53 work_in_output: Use the output directory as the work directory and
54 don't write to a separate output directory.
59 self.keep_outputs = False
61 self.work_in_output = False
64 class ResultThread(threading.Thread):
65 """This thread processes results from builder threads.
67 It simply passes the results on to the builder. There is only one
68 result thread, and this helps to serialise the build output.
70 def __init__(self, builder):
71 """Set up a new result thread
74 builder: Builder which will be sent each result
76 threading.Thread.__init__(self)
77 self.builder = builder
80 """Called to start up the result thread.
82 We collect the next result job and pass it on to the build.
85 result = self.builder.out_queue.get()
86 self.builder.process_result(result)
87 self.builder.out_queue.task_done()
90 class BuilderThread(threading.Thread):
91 """This thread builds U-Boot for a particular board.
93 An input queue provides each new job. We run 'make' to build U-Boot
94 and then pass the results on to the output queue.
97 builder: The builder which contains information we might need
98 thread_num: Our thread number (0-n-1), used to decide on a
99 temporary directory. If this is -1 then there are no threads
100 and we are the (only) main process
101 mrproper: Use 'make mrproper' before each reconfigure
102 per_board_out_dir: True to build in a separate persistent directory per
103 board rather than a thread-specific directory
104 test_exception: Used for testing; True to raise an exception instead of
105 reporting the build result
107 def __init__(self, builder, thread_num, mrproper, per_board_out_dir,
108 test_exception=False):
109 """Set up a new builder thread"""
110 threading.Thread.__init__(self)
111 self.builder = builder
112 self.thread_num = thread_num
113 self.mrproper = mrproper
114 self.per_board_out_dir = per_board_out_dir
115 self.test_exception = test_exception
116 self.toolchain = None
118 def make(self, commit, brd, stage, cwd, *args, **kwargs):
119 """Run 'make' on a particular commit and board.
121 The source code will already be checked out, so the 'commit'
122 argument is only for information.
125 commit: Commit object that is being built
126 brd: Board object that is being built
127 stage: Stage of the build. Valid stages are:
128 mrproper - can be called to clean source
129 config - called to configure for a board
130 build - the main make invocation - it does the build
131 args: A list of arguments to pass to 'make'
132 kwargs: A list of keyword arguments to pass to command.run_pipe()
137 return self.builder.do_make(commit, brd, stage, cwd, *args,
140 def _build_args(self, brd, out_dir, out_rel_dir, work_dir, commit_upto):
141 """Set up arguments to the args list based on the settings
144 brd (Board): Board to create arguments for
145 out_dir (str): Path to output directory containing the files
146 out_rel_dir (str): Output directory relative to the current dir
147 work_dir (str): Directory to which the source will be checked out
148 commit_upto (int): Commit number to build (0...n-1)
152 list of str: Arguments to pass to make
153 str: Current working directory, or None if no commit
154 str: Source directory (typically the work directory)
158 src_dir = os.path.realpath(work_dir)
159 if not self.builder.in_tree:
160 if commit_upto is None:
161 # In this case we are building in the original source directory
162 # (i.e. the current directory where buildman is invoked. The
163 # output directory is set to this thread's selected work
166 # Symlinks can confuse U-Boot's Makefile since we may use '..'
167 # in our path, so remove them.
168 real_dir = os.path.realpath(out_dir)
169 args.append(f'O={real_dir}')
171 src_dir = os.getcwd()
173 args.append(f'O={out_rel_dir}')
174 if self.builder.verbose_build:
178 if self.builder.num_jobs is not None:
179 args.extend(['-j', str(self.builder.num_jobs)])
180 if self.builder.warnings_as_errors:
181 args.append('KCFLAGS=-Werror')
182 args.append('HOSTCFLAGS=-Werror')
183 if self.builder.allow_missing:
184 args.append('BINMAN_ALLOW_MISSING=1')
185 if self.builder.no_lto:
186 args.append('NO_LTO=1')
187 if self.builder.reproducible_builds:
188 args.append('SOURCE_DATE_EPOCH=0')
189 args.extend(self.builder.toolchains.GetMakeArguments(brd))
190 args.extend(self.toolchain.MakeArgs())
191 return args, cwd, src_dir
193 def run_commit(self, commit_upto, brd, work_dir, do_config, config_only,
194 force_build, force_build_failures, work_in_output,
196 """Build a particular commit.
198 If the build is already done, and we are not forcing a build, we skip
199 the build and just return the previously-saved results.
202 commit_upto: Commit number to build (0...n-1)
203 brd: Board object to build
204 work_dir: Directory to which the source will be checked out
205 do_config: True to run a make <board>_defconfig on the source
206 config_only: Only configure the source, do not build it
207 force_build: Force a build even if one was previously done
208 force_build_failures: Force a bulid if the previous result showed
210 work_in_output: Use the output directory as the work directory and
211 don't write to a separate output directory.
212 adjust_cfg (list of str): List of changes to make to .config file
213 before building. Each is one of (where C is either CONFIG_xxx
217 C=val to set the value of C (val must have quotes if C is
222 - CommandResult object containing the results of the build
223 - boolean indicating whether 'make config' is still needed
225 # Create a default result - it will be overwritte by the call to
226 # self.make() below, in the event that we do a build.
227 result = command.CommandResult()
228 result.return_code = 0
229 if work_in_output or self.builder.in_tree:
233 if self.per_board_out_dir:
234 out_rel_dir = os.path.join('..', brd.target)
236 out_rel_dir = 'build'
237 out_dir = os.path.join(work_dir, out_rel_dir)
239 # Check if the job was already completed last time
240 done_file = self.builder.get_done_file(commit_upto, brd.target)
241 result.already_done = os.path.exists(done_file)
242 will_build = (force_build or force_build_failures or
243 not result.already_done)
244 if result.already_done:
245 # Get the return code from that build and use it
246 with open(done_file, 'r', encoding='utf-8') as outf:
248 result.return_code = int(outf.readline())
250 # The file may be empty due to running out of disk space.
252 result.return_code = RETURN_CODE_RETRY
254 # Check the signal that the build needs to be retried
255 if result.return_code == RETURN_CODE_RETRY:
258 err_file = self.builder.get_err_file(commit_upto, brd.target)
259 if os.path.exists(err_file) and os.stat(err_file).st_size:
260 result.stderr = 'bad'
261 elif not force_build:
262 # The build passed, so no need to build it again
266 # We are going to have to build it. First, get a toolchain
267 if not self.toolchain:
269 self.toolchain = self.builder.toolchains.Select(brd.arch)
270 except ValueError as err:
271 result.return_code = 10
273 result.stderr = str(err)
274 # TODO(sjg@chromium.org): This gets swallowed, but needs
278 # Checkout the right commit
279 if self.builder.commits:
280 commit = self.builder.commits[commit_upto]
281 if self.builder.checkout:
282 git_dir = os.path.join(work_dir, '.git')
283 gitutil.checkout(commit.hash, git_dir, work_dir,
288 # Set up the environment and command line
289 env = self.toolchain.MakeEnvironment(self.builder.full_path)
292 args, cwd, src_dir = self._build_args(brd, out_dir, out_rel_dir,
293 work_dir, commit_upto)
294 config_args = [f'{brd.target}_defconfig']
297 # Remove any output targets. Since we use a build directory that
298 # was previously used by another board, it may have produced an
299 # SPL image. If we don't remove it (i.e. see do_config and
300 # self.mrproper below) then it will appear to be the output of
301 # this build, even if it does not produce SPL images.
302 for elf in BASE_ELF_FILENAMES:
303 fname = os.path.join(out_dir, elf)
304 if os.path.exists(fname):
307 # If we need to reconfigure, do that now
308 cfg_file = os.path.join(out_dir, '.config')
310 if do_config or adjust_cfg:
312 result = self.make(commit, brd, 'mrproper', cwd,
313 'mrproper', *args, env=env)
314 config_out += result.combined
315 cmd_list.append([self.builder.gnu_make, 'mrproper',
317 result = self.make(commit, brd, 'config', cwd,
318 *(args + config_args), env=env)
319 cmd_list.append([self.builder.gnu_make] + args +
321 config_out += result.combined
322 do_config = False # No need to configure next time
324 cfgutil.adjust_cfg_file(cfg_file, adjust_cfg)
325 if result.return_code == 0:
328 result = self.make(commit, brd, 'build', cwd, *args,
330 cmd_list.append([self.builder.gnu_make] + args)
331 if (result.return_code == 2 and
332 ('Some images are invalid' in result.stderr)):
333 # This is handled later by the check for output in
335 result.return_code = 0
337 errs = cfgutil.check_cfg_file(cfg_file, adjust_cfg)
339 result.stderr += errs
340 result.return_code = 1
341 result.stderr = result.stderr.replace(src_dir + '/', '')
342 if self.builder.verbose_build:
343 result.stdout = config_out + result.stdout
344 result.cmd_list = cmd_list
346 result.return_code = 1
347 result.stderr = f'No tool chain for {brd.arch}\n'
348 result.already_done = False
350 result.toolchain = self.toolchain
352 result.commit_upto = commit_upto
353 result.out_dir = out_dir
354 return result, do_config
356 def _write_result(self, result, keep_outputs, work_in_output):
357 """Write a built result to the output directory.
360 result: CommandResult object containing result to write
361 keep_outputs: True to store the output binaries, False
363 work_in_output: Use the output directory as the work directory and
364 don't write to a separate output directory.
366 # If we think this might have been aborted with Ctrl-C, record the
367 # failure but not that we are 'done' with this board. A retry may fix
369 maybe_aborted = result.stderr and 'No child processes' in result.stderr
371 if result.return_code >= 0 and result.already_done:
374 # Write the output and stderr
375 output_dir = self.builder.get_output_dir(result.commit_upto)
377 build_dir = self.builder.get_build_dir(result.commit_upto,
381 outfile = os.path.join(build_dir, 'log')
382 with open(outfile, 'w', encoding='utf-8') as outf:
384 outf.write(result.stdout)
386 errfile = self.builder.get_err_file(result.commit_upto,
389 with open(errfile, 'w', encoding='utf-8') as outf:
390 outf.write(result.stderr)
391 elif os.path.exists(errfile):
395 if result.return_code < 0:
399 # Write the build result and toolchain information.
400 done_file = self.builder.get_done_file(result.commit_upto,
402 with open(done_file, 'w', encoding='utf-8') as outf:
404 # Special code to indicate we need to retry
405 outf.write(f'{RETURN_CODE_RETRY}')
407 outf.write(f'{result.return_code}')
408 with open(os.path.join(build_dir, 'toolchain'), 'w',
409 encoding='utf-8') as outf:
410 print('gcc', result.toolchain.gcc, file=outf)
411 print('path', result.toolchain.path, file=outf)
412 print('cross', result.toolchain.cross, file=outf)
413 print('arch', result.toolchain.arch, file=outf)
414 outf.write(f'{result.return_code}')
416 # Write out the image and function size information and an objdump
417 env = result.toolchain.MakeEnvironment(self.builder.full_path)
418 with open(os.path.join(build_dir, 'out-env'), 'wb') as outf:
419 for var in sorted(env.keys()):
420 outf.write(b'%s="%s"' % (var, env[var]))
422 with open(os.path.join(build_dir, 'out-cmd'), 'w',
423 encoding='utf-8') as outf:
424 for cmd in result.cmd_list:
425 print(' '.join(cmd), file=outf)
428 for fname in BASE_ELF_FILENAMES:
429 cmd = [f'{self.toolchain.cross}nm', '--size-sort', fname]
430 nm_result = command.run_pipe([cmd], capture=True,
431 capture_stderr=True, cwd=result.out_dir,
432 raise_on_error=False, env=env)
434 nm_fname = self.builder.get_func_sizes_file(
435 result.commit_upto, result.brd.target, fname)
436 with open(nm_fname, 'w', encoding='utf-8') as outf:
437 print(nm_result.stdout, end=' ', file=outf)
439 cmd = [f'{self.toolchain.cross}objdump', '-h', fname]
440 dump_result = command.run_pipe([cmd], capture=True,
441 capture_stderr=True, cwd=result.out_dir,
442 raise_on_error=False, env=env)
444 if dump_result.stdout:
445 objdump = self.builder.get_objdump_file(result.commit_upto,
446 result.brd.target, fname)
447 with open(objdump, 'w', encoding='utf-8') as outf:
448 print(dump_result.stdout, end=' ', file=outf)
449 for line in dump_result.stdout.splitlines():
450 fields = line.split()
451 if len(fields) > 5 and fields[1] == '.rodata':
452 rodata_size = fields[2]
454 cmd = [f'{self.toolchain.cross}size', fname]
455 size_result = command.run_pipe([cmd], capture=True,
456 capture_stderr=True, cwd=result.out_dir,
457 raise_on_error=False, env=env)
458 if size_result.stdout:
459 lines.append(size_result.stdout.splitlines()[1] + ' ' +
462 # Extract the environment from U-Boot and dump it out
463 cmd = [f'{self.toolchain.cross}objcopy', '-O', 'binary',
464 '-j', '.rodata.default_environment',
465 'env/built-in.o', 'uboot.env']
466 command.run_pipe([cmd], capture=True,
467 capture_stderr=True, cwd=result.out_dir,
468 raise_on_error=False, env=env)
469 if not work_in_output:
470 self.copy_files(result.out_dir, build_dir, '', ['uboot.env'])
472 # Write out the image sizes file. This is similar to the output
473 # of binutil's 'size' utility, but it omits the header line and
474 # adds an additional hex value at the end of each line for the
477 sizes = self.builder.get_sizes_file(result.commit_upto,
479 with open(sizes, 'w', encoding='utf-8') as outf:
480 print('\n'.join(lines), file=outf)
482 if not work_in_output:
483 # Write out the configuration files, with a special case for SPL
484 for dirname in ['', 'spl', 'tpl']:
486 result.out_dir, build_dir, dirname,
487 ['u-boot.cfg', 'spl/u-boot-spl.cfg', 'tpl/u-boot-tpl.cfg',
488 '.config', 'include/autoconf.mk',
489 'include/generated/autoconf.h'])
491 # Now write the actual build output
494 result.out_dir, build_dir, '',
495 ['u-boot*', '*.bin', '*.map', '*.img', 'MLO', 'SPL',
496 'include/autoconf.mk', 'spl/u-boot-spl*'])
498 def copy_files(self, out_dir, build_dir, dirname, patterns):
499 """Copy files from the build directory to the output.
502 out_dir: Path to output directory containing the files
503 build_dir: Place to copy the files
504 dirname: Source directory, '' for normal U-Boot, 'spl' for SPL
505 patterns: A list of filenames (strings) to copy, each relative
506 to the build directory
508 for pattern in patterns:
509 file_list = glob.glob(os.path.join(out_dir, dirname, pattern))
510 for fname in file_list:
511 target = os.path.basename(fname)
513 base, ext = os.path.splitext(target)
515 target = f'{base}-{dirname}{ext}'
516 shutil.copy(fname, os.path.join(build_dir, target))
518 def _send_result(self, result):
519 """Send a result to the builder for processing
522 result: CommandResult object containing the results of the build
525 ValueError if self.test_exception is true (for testing)
527 if self.test_exception:
528 raise ValueError('test exception')
529 if self.thread_num != -1:
530 self.builder.out_queue.put(result)
532 self.builder.process_result(result)
534 def run_job(self, job):
537 A job consists of a building a list of commits for a particular board.
543 List of Result objects
546 work_dir = self.builder.get_thread_dir(self.thread_num)
547 self.toolchain = None
549 # Run 'make board_defconfig' on the first commit
553 for commit_upto in range(0, len(job.commits), job.step):
554 result, request_config = self.run_commit(commit_upto, brd,
555 work_dir, do_config, self.builder.config_only,
556 force_build or self.builder.force_build,
557 self.builder.force_build_failures,
558 job.work_in_output, job.adjust_cfg)
559 failed = result.return_code or result.stderr
560 did_config = do_config
561 if failed and not do_config:
562 # If our incremental build failed, try building again
564 if self.builder.force_config_on_failure:
565 result, request_config = self.run_commit(commit_upto,
566 brd, work_dir, True, False, True, False,
567 job.work_in_output, job.adjust_cfg)
569 if not self.builder.force_reconfig:
570 do_config = request_config
572 # If we built that commit, then config is done. But if we got
573 # an warning, reconfig next time to force it to build the same
574 # files that created warnings this time. Otherwise an
575 # incremental build may not build the same file, and we will
576 # think that the warning has gone away.
577 # We could avoid this by using -Werror everywhere...
578 # For errors, the problem doesn't happen, since presumably
579 # the build stopped and didn't generate output, so will retry
580 # that file next time. So we could detect warnings and deal
581 # with them specially here. For now, we just reconfigure if
582 # anything goes work.
583 # Of course this is substantially slower if there are build
584 # errors/warnings (e.g. 2-3x slower even if only 10% of builds
586 if (failed and not result.already_done and not did_config and
587 self.builder.force_config_on_failure):
588 # If this build failed, try the next one with a
590 # Sometimes if the board_config.h file changes it can mess
591 # with dependencies, and we get:
592 # make: *** No rule to make target `include/autoconf.mk',
593 # needed by `depend'.
598 if self.builder.force_config_on_failure:
601 result.commit_upto = commit_upto
602 if result.return_code < 0:
603 raise ValueError('Interrupt')
605 # We have the build results, so output the result
606 self._write_result(result, job.keep_outputs, job.work_in_output)
607 self._send_result(result)
609 # Just build the currently checked-out build
610 result, request_config = self.run_commit(None, brd, work_dir, True,
611 self.builder.config_only, True,
612 self.builder.force_build_failures, job.work_in_output,
614 result.commit_upto = 0
615 self._write_result(result, job.keep_outputs, job.work_in_output)
616 self._send_result(result)
619 """Our thread's run function
621 This thread picks a job from the queue, runs it, and then goes to the
625 job = self.builder.queue.get()
628 except Exception as exc:
629 print('Thread exception (use -T0 to run without threads):',
631 self.builder.thread_exceptions.append(exc)
632 self.builder.queue.task_done()