buildman: Move more things into _build_args()
[platform/kernel/u-boot.git] / tools / buildman / builderthread.py
1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2014 Google, Inc
3 #
4
5 """Implementation the bulider threads
6
7 This module provides the BuilderThread class, which handles calling the builder
8 based on the jobs provided.
9 """
10
11 import errno
12 import glob
13 import os
14 import shutil
15 import sys
16 import threading
17
18 from buildman import cfgutil
19 from patman import gitutil
20 from u_boot_pylib import command
21
22 RETURN_CODE_RETRY = -1
23 BASE_ELF_FILENAMES = ['u-boot', 'spl/u-boot-spl', 'tpl/u-boot-tpl']
24
25 def mkdir(dirname, parents = False):
26     """Make a directory if it doesn't already exist.
27
28     Args:
29         dirname: Directory to create
30     """
31     try:
32         if parents:
33             os.makedirs(dirname)
34         else:
35             os.mkdir(dirname)
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}'!")
40                 sys.exit(1)
41         else:
42             raise
43
44 # pylint: disable=R0903
45 class BuilderJob:
46     """Holds information about a job to be performed by a thread
47
48     Members:
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.
55     """
56     def __init__(self):
57         self.brd = None
58         self.commits = []
59         self.keep_outputs = False
60         self.step = 1
61         self.work_in_output = False
62
63
64 class ResultThread(threading.Thread):
65     """This thread processes results from builder threads.
66
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.
69     """
70     def __init__(self, builder):
71         """Set up a new result thread
72
73         Args:
74             builder: Builder which will be sent each result
75         """
76         threading.Thread.__init__(self)
77         self.builder = builder
78
79     def run(self):
80         """Called to start up the result thread.
81
82         We collect the next result job and pass it on to the build.
83         """
84         while True:
85             result = self.builder.out_queue.get()
86             self.builder.process_result(result)
87             self.builder.out_queue.task_done()
88
89
90 class BuilderThread(threading.Thread):
91     """This thread builds U-Boot for a particular board.
92
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.
95
96     Members:
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
106     """
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
117
118     def make(self, commit, brd, stage, cwd, *args, **kwargs):
119         """Run 'make' on a particular commit and board.
120
121         The source code will already be checked out, so the 'commit'
122         argument is only for information.
123
124         Args:
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()
133
134         Returns:
135             CommandResult object
136         """
137         return self.builder.do_make(commit, brd, stage, cwd, *args,
138                 **kwargs)
139
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
142
143         Args:
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)
149
150         Returns:
151             tuple:
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)
155         """
156         args = []
157         cwd = work_dir
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
164                 # directory.
165                 #
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}')
170                 cwd = None
171                 src_dir = os.getcwd()
172             else:
173                 args.append(f'O={out_rel_dir}')
174         if self.builder.verbose_build:
175             args.append('V=1')
176         else:
177             args.append('-s')
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
192
193     def run_commit(self, commit_upto, brd, work_dir, do_config, config_only,
194                   force_build, force_build_failures, work_in_output,
195                   adjust_cfg):
196         """Build a particular commit.
197
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.
200
201         Args:
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
209                 failure
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
214                 or just xxx):
215                      C to enable C
216                      ~C to disable C
217                      C=val to set the value of C (val must have quotes if C is
218                          a string Kconfig
219
220         Returns:
221             tuple containing:
222                 - CommandResult object containing the results of the build
223                 - boolean indicating whether 'make config' is still needed
224         """
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:
230             out_rel_dir = None
231             out_dir = work_dir
232         else:
233             if self.per_board_out_dir:
234                 out_rel_dir = os.path.join('..', brd.target)
235             else:
236                 out_rel_dir = 'build'
237             out_dir = os.path.join(work_dir, out_rel_dir)
238
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:
247                 try:
248                     result.return_code = int(outf.readline())
249                 except ValueError:
250                     # The file may be empty due to running out of disk space.
251                     # Try a rebuild
252                     result.return_code = RETURN_CODE_RETRY
253
254             # Check the signal that the build needs to be retried
255             if result.return_code == RETURN_CODE_RETRY:
256                 will_build = True
257             elif will_build:
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
263                     will_build = False
264
265         if will_build:
266             # We are going to have to build it. First, get a toolchain
267             if not self.toolchain:
268                 try:
269                     self.toolchain = self.builder.toolchains.Select(brd.arch)
270                 except ValueError as err:
271                     result.return_code = 10
272                     result.stdout = ''
273                     result.stderr = str(err)
274                     # TODO(sjg@chromium.org): This gets swallowed, but needs
275                     # to be reported.
276
277             if self.toolchain:
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,
284                                          force=True)
285                 else:
286                     commit = 'current'
287
288                 # Set up the environment and command line
289                 env = self.toolchain.MakeEnvironment(self.builder.full_path)
290                 mkdir(out_dir)
291
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']
295                 config_out = ''
296
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):
305                         os.remove(fname)
306
307                 # If we need to reconfigure, do that now
308                 cfg_file = os.path.join(out_dir, '.config')
309                 cmd_list = []
310                 if do_config or adjust_cfg:
311                     if self.mrproper:
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',
316                                          *args])
317                     result = self.make(commit, brd, 'config', cwd,
318                             *(args + config_args), env=env)
319                     cmd_list.append([self.builder.gnu_make] + args +
320                                     config_args)
321                     config_out += result.combined
322                     do_config = False   # No need to configure next time
323                     if adjust_cfg:
324                         cfgutil.adjust_cfg_file(cfg_file, adjust_cfg)
325                 if result.return_code == 0:
326                     if config_only:
327                         args.append('cfg')
328                     result = self.make(commit, brd, 'build', cwd, *args,
329                             env=env)
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
334                         # stderr
335                         result.return_code = 0
336                     if adjust_cfg:
337                         errs = cfgutil.check_cfg_file(cfg_file, adjust_cfg)
338                         if errs:
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
345             else:
346                 result.return_code = 1
347                 result.stderr = f'No tool chain for {brd.arch}\n'
348             result.already_done = False
349
350         result.toolchain = self.toolchain
351         result.brd = brd
352         result.commit_upto = commit_upto
353         result.out_dir = out_dir
354         return result, do_config
355
356     def _write_result(self, result, keep_outputs, work_in_output):
357         """Write a built result to the output directory.
358
359         Args:
360             result: CommandResult object containing result to write
361             keep_outputs: True to store the output binaries, False
362                 to delete them
363             work_in_output: Use the output directory as the work directory and
364                 don't write to a separate output directory.
365         """
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
368         # it.
369         maybe_aborted = result.stderr and 'No child processes' in result.stderr
370
371         if result.return_code >= 0 and result.already_done:
372             return
373
374         # Write the output and stderr
375         output_dir = self.builder.get_output_dir(result.commit_upto)
376         mkdir(output_dir)
377         build_dir = self.builder.get_build_dir(result.commit_upto,
378                 result.brd.target)
379         mkdir(build_dir)
380
381         outfile = os.path.join(build_dir, 'log')
382         with open(outfile, 'w', encoding='utf-8') as outf:
383             if result.stdout:
384                 outf.write(result.stdout)
385
386         errfile = self.builder.get_err_file(result.commit_upto,
387                 result.brd.target)
388         if result.stderr:
389             with open(errfile, 'w', encoding='utf-8') as outf:
390                 outf.write(result.stderr)
391         elif os.path.exists(errfile):
392             os.remove(errfile)
393
394         # Fatal error
395         if result.return_code < 0:
396             return
397
398         if result.toolchain:
399             # Write the build result and toolchain information.
400             done_file = self.builder.get_done_file(result.commit_upto,
401                     result.brd.target)
402             with open(done_file, 'w', encoding='utf-8') as outf:
403                 if maybe_aborted:
404                     # Special code to indicate we need to retry
405                     outf.write(f'{RETURN_CODE_RETRY}')
406                 else:
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}')
415
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]))
421
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)
426
427             lines = []
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)
433                 if nm_result.stdout:
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)
438
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)
443                 rodata_size = ''
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]
453
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] + ' ' +
460                                  rodata_size)
461
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'])
471
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
475             # rodata size
476             if lines:
477                 sizes = self.builder.get_sizes_file(result.commit_upto,
478                                 result.brd.target)
479                 with open(sizes, 'w', encoding='utf-8') as outf:
480                     print('\n'.join(lines), file=outf)
481
482         if not work_in_output:
483             # Write out the configuration files, with a special case for SPL
484             for dirname in ['', 'spl', 'tpl']:
485                 self.copy_files(
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'])
490
491             # Now write the actual build output
492             if keep_outputs:
493                 self.copy_files(
494                     result.out_dir, build_dir, '',
495                     ['u-boot*', '*.bin', '*.map', '*.img', 'MLO', 'SPL',
496                      'include/autoconf.mk', 'spl/u-boot-spl*'])
497
498     def copy_files(self, out_dir, build_dir, dirname, patterns):
499         """Copy files from the build directory to the output.
500
501         Args:
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
507         """
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)
512                 if dirname:
513                     base, ext = os.path.splitext(target)
514                     if ext:
515                         target = f'{base}-{dirname}{ext}'
516                 shutil.copy(fname, os.path.join(build_dir, target))
517
518     def _send_result(self, result):
519         """Send a result to the builder for processing
520
521         Args:
522             result: CommandResult object containing the results of the build
523
524         Raises:
525             ValueError if self.test_exception is true (for testing)
526         """
527         if self.test_exception:
528             raise ValueError('test exception')
529         if self.thread_num != -1:
530             self.builder.out_queue.put(result)
531         else:
532             self.builder.process_result(result)
533
534     def run_job(self, job):
535         """Run a single job
536
537         A job consists of a building a list of commits for a particular board.
538
539         Args:
540             job: Job to build
541
542         Returns:
543             List of Result objects
544         """
545         brd = job.brd
546         work_dir = self.builder.get_thread_dir(self.thread_num)
547         self.toolchain = None
548         if job.commits:
549             # Run 'make board_defconfig' on the first commit
550             do_config = True
551             commit_upto  = 0
552             force_build = False
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
563                     # with a reconfig.
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)
568                         did_config = True
569                 if not self.builder.force_reconfig:
570                     do_config = request_config
571
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
585                 # have problems).
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
589                     # reconfigure.
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'.
594                     do_config = True
595                     force_build = True
596                 else:
597                     force_build = False
598                     if self.builder.force_config_on_failure:
599                         if failed:
600                             do_config = True
601                     result.commit_upto = commit_upto
602                     if result.return_code < 0:
603                         raise ValueError('Interrupt')
604
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)
608         else:
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,
613                         job.adjust_cfg)
614             result.commit_upto = 0
615             self._write_result(result, job.keep_outputs, job.work_in_output)
616             self._send_result(result)
617
618     def run(self):
619         """Our thread's run function
620
621         This thread picks a job from the queue, runs it, and then goes to the
622         next job.
623         """
624         while True:
625             job = self.builder.queue.get()
626             try:
627                 self.run_job(job)
628             except Exception as exc:
629                 print('Thread exception (use -T0 to run without threads):',
630                       exc)
631                 self.builder.thread_exceptions.append(exc)
632             self.builder.queue.task_done()