builder.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2013 The Chromium OS Authors.
  3. #
  4. # Bloat-o-meter code used here Copyright 2004 Matt Mackall <mpm@selenic.com>
  5. #
  6. import collections
  7. from datetime import datetime, timedelta
  8. import glob
  9. import os
  10. import re
  11. import queue
  12. import shutil
  13. import signal
  14. import string
  15. import sys
  16. import threading
  17. import time
  18. import builderthread
  19. import command
  20. import gitutil
  21. import terminal
  22. from terminal import Print
  23. import toolchain
  24. """
  25. Theory of Operation
  26. Please see README for user documentation, and you should be familiar with
  27. that before trying to make sense of this.
  28. Buildman works by keeping the machine as busy as possible, building different
  29. commits for different boards on multiple CPUs at once.
  30. The source repo (self.git_dir) contains all the commits to be built. Each
  31. thread works on a single board at a time. It checks out the first commit,
  32. configures it for that board, then builds it. Then it checks out the next
  33. commit and builds it (typically without re-configuring). When it runs out
  34. of commits, it gets another job from the builder and starts again with that
  35. board.
  36. Clearly the builder threads could work either way - they could check out a
  37. commit and then built it for all boards. Using separate directories for each
  38. commit/board pair they could leave their build product around afterwards
  39. also.
  40. The intent behind building a single board for multiple commits, is to make
  41. use of incremental builds. Since each commit is built incrementally from
  42. the previous one, builds are faster. Reconfiguring for a different board
  43. removes all intermediate object files.
  44. Many threads can be working at once, but each has its own working directory.
  45. When a thread finishes a build, it puts the output files into a result
  46. directory.
  47. The base directory used by buildman is normally '../<branch>', i.e.
  48. a directory higher than the source repository and named after the branch
  49. being built.
  50. Within the base directory, we have one subdirectory for each commit. Within
  51. that is one subdirectory for each board. Within that is the build output for
  52. that commit/board combination.
  53. Buildman also create working directories for each thread, in a .bm-work/
  54. subdirectory in the base dir.
  55. As an example, say we are building branch 'us-net' for boards 'sandbox' and
  56. 'seaboard', and say that us-net has two commits. We will have directories
  57. like this:
  58. us-net/ base directory
  59. 01_of_02_g4ed4ebc_net--Add-tftp-speed-/
  60. sandbox/
  61. u-boot.bin
  62. seaboard/
  63. u-boot.bin
  64. 02_of_02_g4ed4ebc_net--Check-tftp-comp/
  65. sandbox/
  66. u-boot.bin
  67. seaboard/
  68. u-boot.bin
  69. .bm-work/
  70. 00/ working directory for thread 0 (contains source checkout)
  71. build/ build output
  72. 01/ working directory for thread 1
  73. build/ build output
  74. ...
  75. u-boot/ source directory
  76. .git/ repository
  77. """
  78. # Possible build outcomes
  79. OUTCOME_OK, OUTCOME_WARNING, OUTCOME_ERROR, OUTCOME_UNKNOWN = list(range(4))
  80. # Translate a commit subject into a valid filename (and handle unicode)
  81. trans_valid_chars = str.maketrans('/: ', '---')
  82. BASE_CONFIG_FILENAMES = [
  83. 'u-boot.cfg', 'u-boot-spl.cfg', 'u-boot-tpl.cfg'
  84. ]
  85. EXTRA_CONFIG_FILENAMES = [
  86. '.config', '.config-spl', '.config-tpl',
  87. 'autoconf.mk', 'autoconf-spl.mk', 'autoconf-tpl.mk',
  88. 'autoconf.h', 'autoconf-spl.h','autoconf-tpl.h',
  89. ]
  90. class Config:
  91. """Holds information about configuration settings for a board."""
  92. def __init__(self, config_filename, target):
  93. self.target = target
  94. self.config = {}
  95. for fname in config_filename:
  96. self.config[fname] = {}
  97. def Add(self, fname, key, value):
  98. self.config[fname][key] = value
  99. def __hash__(self):
  100. val = 0
  101. for fname in self.config:
  102. for key, value in self.config[fname].items():
  103. print(key, value)
  104. val = val ^ hash(key) & hash(value)
  105. return val
  106. class Environment:
  107. """Holds information about environment variables for a board."""
  108. def __init__(self, target):
  109. self.target = target
  110. self.environment = {}
  111. def Add(self, key, value):
  112. self.environment[key] = value
  113. class Builder:
  114. """Class for building U-Boot for a particular commit.
  115. Public members: (many should ->private)
  116. already_done: Number of builds already completed
  117. base_dir: Base directory to use for builder
  118. checkout: True to check out source, False to skip that step.
  119. This is used for testing.
  120. col: terminal.Color() object
  121. count: Number of commits to build
  122. do_make: Method to call to invoke Make
  123. fail: Number of builds that failed due to error
  124. force_build: Force building even if a build already exists
  125. force_config_on_failure: If a commit fails for a board, disable
  126. incremental building for the next commit we build for that
  127. board, so that we will see all warnings/errors again.
  128. force_build_failures: If a previously-built build (i.e. built on
  129. a previous run of buildman) is marked as failed, rebuild it.
  130. git_dir: Git directory containing source repository
  131. last_line_len: Length of the last line we printed (used for erasing
  132. it with new progress information)
  133. num_jobs: Number of jobs to run at once (passed to make as -j)
  134. num_threads: Number of builder threads to run
  135. out_queue: Queue of results to process
  136. re_make_err: Compiled regular expression for ignore_lines
  137. queue: Queue of jobs to run
  138. threads: List of active threads
  139. toolchains: Toolchains object to use for building
  140. upto: Current commit number we are building (0.count-1)
  141. warned: Number of builds that produced at least one warning
  142. force_reconfig: Reconfigure U-Boot on each comiit. This disables
  143. incremental building, where buildman reconfigures on the first
  144. commit for a baord, and then just does an incremental build for
  145. the following commits. In fact buildman will reconfigure and
  146. retry for any failing commits, so generally the only effect of
  147. this option is to slow things down.
  148. in_tree: Build U-Boot in-tree instead of specifying an output
  149. directory separate from the source code. This option is really
  150. only useful for testing in-tree builds.
  151. Private members:
  152. _base_board_dict: Last-summarised Dict of boards
  153. _base_err_lines: Last-summarised list of errors
  154. _base_warn_lines: Last-summarised list of warnings
  155. _build_period_us: Time taken for a single build (float object).
  156. _complete_delay: Expected delay until completion (timedelta)
  157. _next_delay_update: Next time we plan to display a progress update
  158. (datatime)
  159. _show_unknown: Show unknown boards (those not built) in summary
  160. _timestamps: List of timestamps for the completion of the last
  161. last _timestamp_count builds. Each is a datetime object.
  162. _timestamp_count: Number of timestamps to keep in our list.
  163. _working_dir: Base working directory containing all threads
  164. """
  165. class Outcome:
  166. """Records a build outcome for a single make invocation
  167. Public Members:
  168. rc: Outcome value (OUTCOME_...)
  169. err_lines: List of error lines or [] if none
  170. sizes: Dictionary of image size information, keyed by filename
  171. - Each value is itself a dictionary containing
  172. values for 'text', 'data' and 'bss', being the integer
  173. size in bytes of each section.
  174. func_sizes: Dictionary keyed by filename - e.g. 'u-boot'. Each
  175. value is itself a dictionary:
  176. key: function name
  177. value: Size of function in bytes
  178. config: Dictionary keyed by filename - e.g. '.config'. Each
  179. value is itself a dictionary:
  180. key: config name
  181. value: config value
  182. environment: Dictionary keyed by environment variable, Each
  183. value is the value of environment variable.
  184. """
  185. def __init__(self, rc, err_lines, sizes, func_sizes, config,
  186. environment):
  187. self.rc = rc
  188. self.err_lines = err_lines
  189. self.sizes = sizes
  190. self.func_sizes = func_sizes
  191. self.config = config
  192. self.environment = environment
  193. def __init__(self, toolchains, base_dir, git_dir, num_threads, num_jobs,
  194. gnu_make='make', checkout=True, show_unknown=True, step=1,
  195. no_subdirs=False, full_path=False, verbose_build=False,
  196. incremental=False, per_board_out_dir=False,
  197. config_only=False, squash_config_y=False,
  198. warnings_as_errors=False):
  199. """Create a new Builder object
  200. Args:
  201. toolchains: Toolchains object to use for building
  202. base_dir: Base directory to use for builder
  203. git_dir: Git directory containing source repository
  204. num_threads: Number of builder threads to run
  205. num_jobs: Number of jobs to run at once (passed to make as -j)
  206. gnu_make: the command name of GNU Make.
  207. checkout: True to check out source, False to skip that step.
  208. This is used for testing.
  209. show_unknown: Show unknown boards (those not built) in summary
  210. step: 1 to process every commit, n to process every nth commit
  211. no_subdirs: Don't create subdirectories when building current
  212. source for a single board
  213. full_path: Return the full path in CROSS_COMPILE and don't set
  214. PATH
  215. verbose_build: Run build with V=1 and don't use 'make -s'
  216. incremental: Always perform incremental builds; don't run make
  217. mrproper when configuring
  218. per_board_out_dir: Build in a separate persistent directory per
  219. board rather than a thread-specific directory
  220. config_only: Only configure each build, don't build it
  221. squash_config_y: Convert CONFIG options with the value 'y' to '1'
  222. warnings_as_errors: Treat all compiler warnings as errors
  223. """
  224. self.toolchains = toolchains
  225. self.base_dir = base_dir
  226. self._working_dir = os.path.join(base_dir, '.bm-work')
  227. self.threads = []
  228. self.do_make = self.Make
  229. self.gnu_make = gnu_make
  230. self.checkout = checkout
  231. self.num_threads = num_threads
  232. self.num_jobs = num_jobs
  233. self.already_done = 0
  234. self.force_build = False
  235. self.git_dir = git_dir
  236. self._show_unknown = show_unknown
  237. self._timestamp_count = 10
  238. self._build_period_us = None
  239. self._complete_delay = None
  240. self._next_delay_update = datetime.now()
  241. self.force_config_on_failure = True
  242. self.force_build_failures = False
  243. self.force_reconfig = False
  244. self._step = step
  245. self.in_tree = False
  246. self._error_lines = 0
  247. self.no_subdirs = no_subdirs
  248. self.full_path = full_path
  249. self.verbose_build = verbose_build
  250. self.config_only = config_only
  251. self.squash_config_y = squash_config_y
  252. self.config_filenames = BASE_CONFIG_FILENAMES
  253. if not self.squash_config_y:
  254. self.config_filenames += EXTRA_CONFIG_FILENAMES
  255. self.warnings_as_errors = warnings_as_errors
  256. self.col = terminal.Color()
  257. self._re_function = re.compile('(.*): In function.*')
  258. self._re_files = re.compile('In file included from.*')
  259. self._re_warning = re.compile('(.*):(\d*):(\d*): warning: .*')
  260. self._re_dtb_warning = re.compile('(.*): Warning .*')
  261. self._re_note = re.compile('(.*):(\d*):(\d*): note: this is the location of the previous.*')
  262. self.queue = queue.Queue()
  263. self.out_queue = queue.Queue()
  264. for i in range(self.num_threads):
  265. t = builderthread.BuilderThread(self, i, incremental,
  266. per_board_out_dir)
  267. t.setDaemon(True)
  268. t.start()
  269. self.threads.append(t)
  270. self.last_line_len = 0
  271. t = builderthread.ResultThread(self)
  272. t.setDaemon(True)
  273. t.start()
  274. self.threads.append(t)
  275. ignore_lines = ['(make.*Waiting for unfinished)', '(Segmentation fault)']
  276. self.re_make_err = re.compile('|'.join(ignore_lines))
  277. # Handle existing graceful with SIGINT / Ctrl-C
  278. signal.signal(signal.SIGINT, self.signal_handler)
  279. def __del__(self):
  280. """Get rid of all threads created by the builder"""
  281. for t in self.threads:
  282. del t
  283. def signal_handler(self, signal, frame):
  284. sys.exit(1)
  285. def SetDisplayOptions(self, show_errors=False, show_sizes=False,
  286. show_detail=False, show_bloat=False,
  287. list_error_boards=False, show_config=False,
  288. show_environment=False):
  289. """Setup display options for the builder.
  290. show_errors: True to show summarised error/warning info
  291. show_sizes: Show size deltas
  292. show_detail: Show detail for each board
  293. show_bloat: Show detail for each function
  294. list_error_boards: Show the boards which caused each error/warning
  295. show_config: Show config deltas
  296. show_environment: Show environment deltas
  297. """
  298. self._show_errors = show_errors
  299. self._show_sizes = show_sizes
  300. self._show_detail = show_detail
  301. self._show_bloat = show_bloat
  302. self._list_error_boards = list_error_boards
  303. self._show_config = show_config
  304. self._show_environment = show_environment
  305. def _AddTimestamp(self):
  306. """Add a new timestamp to the list and record the build period.
  307. The build period is the length of time taken to perform a single
  308. build (one board, one commit).
  309. """
  310. now = datetime.now()
  311. self._timestamps.append(now)
  312. count = len(self._timestamps)
  313. delta = self._timestamps[-1] - self._timestamps[0]
  314. seconds = delta.total_seconds()
  315. # If we have enough data, estimate build period (time taken for a
  316. # single build) and therefore completion time.
  317. if count > 1 and self._next_delay_update < now:
  318. self._next_delay_update = now + timedelta(seconds=2)
  319. if seconds > 0:
  320. self._build_period = float(seconds) / count
  321. todo = self.count - self.upto
  322. self._complete_delay = timedelta(microseconds=
  323. self._build_period * todo * 1000000)
  324. # Round it
  325. self._complete_delay -= timedelta(
  326. microseconds=self._complete_delay.microseconds)
  327. if seconds > 60:
  328. self._timestamps.popleft()
  329. count -= 1
  330. def ClearLine(self, length):
  331. """Clear any characters on the current line
  332. Make way for a new line of length 'length', by outputting enough
  333. spaces to clear out the old line. Then remember the new length for
  334. next time.
  335. Args:
  336. length: Length of new line, in characters
  337. """
  338. if length < self.last_line_len:
  339. Print(' ' * (self.last_line_len - length), newline=False)
  340. Print('\r', newline=False)
  341. self.last_line_len = length
  342. sys.stdout.flush()
  343. def SelectCommit(self, commit, checkout=True):
  344. """Checkout the selected commit for this build
  345. """
  346. self.commit = commit
  347. if checkout and self.checkout:
  348. gitutil.Checkout(commit.hash)
  349. def Make(self, commit, brd, stage, cwd, *args, **kwargs):
  350. """Run make
  351. Args:
  352. commit: Commit object that is being built
  353. brd: Board object that is being built
  354. stage: Stage that we are at (mrproper, config, build)
  355. cwd: Directory where make should be run
  356. args: Arguments to pass to make
  357. kwargs: Arguments to pass to command.RunPipe()
  358. """
  359. cmd = [self.gnu_make] + list(args)
  360. result = command.RunPipe([cmd], capture=True, capture_stderr=True,
  361. cwd=cwd, raise_on_error=False, infile='/dev/null', **kwargs)
  362. if self.verbose_build:
  363. result.stdout = '%s\n' % (' '.join(cmd)) + result.stdout
  364. result.combined = '%s\n' % (' '.join(cmd)) + result.combined
  365. return result
  366. def ProcessResult(self, result):
  367. """Process the result of a build, showing progress information
  368. Args:
  369. result: A CommandResult object, which indicates the result for
  370. a single build
  371. """
  372. col = terminal.Color()
  373. if result:
  374. target = result.brd.target
  375. self.upto += 1
  376. if result.return_code != 0:
  377. self.fail += 1
  378. elif result.stderr:
  379. self.warned += 1
  380. if result.already_done:
  381. self.already_done += 1
  382. if self._verbose:
  383. Print('\r', newline=False)
  384. self.ClearLine(0)
  385. boards_selected = {target : result.brd}
  386. self.ResetResultSummary(boards_selected)
  387. self.ProduceResultSummary(result.commit_upto, self.commits,
  388. boards_selected)
  389. else:
  390. target = '(starting)'
  391. # Display separate counts for ok, warned and fail
  392. ok = self.upto - self.warned - self.fail
  393. line = '\r' + self.col.Color(self.col.GREEN, '%5d' % ok)
  394. line += self.col.Color(self.col.YELLOW, '%5d' % self.warned)
  395. line += self.col.Color(self.col.RED, '%5d' % self.fail)
  396. name = ' /%-5d ' % self.count
  397. # Add our current completion time estimate
  398. self._AddTimestamp()
  399. if self._complete_delay:
  400. name += '%s : ' % self._complete_delay
  401. # When building all boards for a commit, we can print a commit
  402. # progress message.
  403. if result and result.commit_upto is None:
  404. name += 'commit %2d/%-3d' % (self.commit_upto + 1,
  405. self.commit_count)
  406. name += target
  407. Print(line + name, newline=False)
  408. length = 16 + len(name)
  409. self.ClearLine(length)
  410. def _GetOutputDir(self, commit_upto):
  411. """Get the name of the output directory for a commit number
  412. The output directory is typically .../<branch>/<commit>.
  413. Args:
  414. commit_upto: Commit number to use (0..self.count-1)
  415. """
  416. commit_dir = None
  417. if self.commits:
  418. commit = self.commits[commit_upto]
  419. subject = commit.subject.translate(trans_valid_chars)
  420. commit_dir = ('%02d_of_%02d_g%s_%s' % (commit_upto + 1,
  421. self.commit_count, commit.hash, subject[:20]))
  422. elif not self.no_subdirs:
  423. commit_dir = 'current'
  424. if not commit_dir:
  425. return self.base_dir
  426. return os.path.join(self.base_dir, commit_dir)
  427. def GetBuildDir(self, commit_upto, target):
  428. """Get the name of the build directory for a commit number
  429. The build directory is typically .../<branch>/<commit>/<target>.
  430. Args:
  431. commit_upto: Commit number to use (0..self.count-1)
  432. target: Target name
  433. """
  434. output_dir = self._GetOutputDir(commit_upto)
  435. return os.path.join(output_dir, target)
  436. def GetDoneFile(self, commit_upto, target):
  437. """Get the name of the done file for a commit number
  438. Args:
  439. commit_upto: Commit number to use (0..self.count-1)
  440. target: Target name
  441. """
  442. return os.path.join(self.GetBuildDir(commit_upto, target), 'done')
  443. def GetSizesFile(self, commit_upto, target):
  444. """Get the name of the sizes file for a commit number
  445. Args:
  446. commit_upto: Commit number to use (0..self.count-1)
  447. target: Target name
  448. """
  449. return os.path.join(self.GetBuildDir(commit_upto, target), 'sizes')
  450. def GetFuncSizesFile(self, commit_upto, target, elf_fname):
  451. """Get the name of the funcsizes file for a commit number and ELF file
  452. Args:
  453. commit_upto: Commit number to use (0..self.count-1)
  454. target: Target name
  455. elf_fname: Filename of elf image
  456. """
  457. return os.path.join(self.GetBuildDir(commit_upto, target),
  458. '%s.sizes' % elf_fname.replace('/', '-'))
  459. def GetObjdumpFile(self, commit_upto, target, elf_fname):
  460. """Get the name of the objdump file for a commit number and ELF file
  461. Args:
  462. commit_upto: Commit number to use (0..self.count-1)
  463. target: Target name
  464. elf_fname: Filename of elf image
  465. """
  466. return os.path.join(self.GetBuildDir(commit_upto, target),
  467. '%s.objdump' % elf_fname.replace('/', '-'))
  468. def GetErrFile(self, commit_upto, target):
  469. """Get the name of the err file for a commit number
  470. Args:
  471. commit_upto: Commit number to use (0..self.count-1)
  472. target: Target name
  473. """
  474. output_dir = self.GetBuildDir(commit_upto, target)
  475. return os.path.join(output_dir, 'err')
  476. def FilterErrors(self, lines):
  477. """Filter out errors in which we have no interest
  478. We should probably use map().
  479. Args:
  480. lines: List of error lines, each a string
  481. Returns:
  482. New list with only interesting lines included
  483. """
  484. out_lines = []
  485. for line in lines:
  486. if not self.re_make_err.search(line):
  487. out_lines.append(line)
  488. return out_lines
  489. def ReadFuncSizes(self, fname, fd):
  490. """Read function sizes from the output of 'nm'
  491. Args:
  492. fd: File containing data to read
  493. fname: Filename we are reading from (just for errors)
  494. Returns:
  495. Dictionary containing size of each function in bytes, indexed by
  496. function name.
  497. """
  498. sym = {}
  499. for line in fd.readlines():
  500. try:
  501. size, type, name = line[:-1].split()
  502. except:
  503. Print("Invalid line in file '%s': '%s'" % (fname, line[:-1]))
  504. continue
  505. if type in 'tTdDbB':
  506. # function names begin with '.' on 64-bit powerpc
  507. if '.' in name[1:]:
  508. name = 'static.' + name.split('.')[0]
  509. sym[name] = sym.get(name, 0) + int(size, 16)
  510. return sym
  511. def _ProcessConfig(self, fname):
  512. """Read in a .config, autoconf.mk or autoconf.h file
  513. This function handles all config file types. It ignores comments and
  514. any #defines which don't start with CONFIG_.
  515. Args:
  516. fname: Filename to read
  517. Returns:
  518. Dictionary:
  519. key: Config name (e.g. CONFIG_DM)
  520. value: Config value (e.g. 1)
  521. """
  522. config = {}
  523. if os.path.exists(fname):
  524. with open(fname) as fd:
  525. for line in fd:
  526. line = line.strip()
  527. if line.startswith('#define'):
  528. values = line[8:].split(' ', 1)
  529. if len(values) > 1:
  530. key, value = values
  531. else:
  532. key = values[0]
  533. value = '1' if self.squash_config_y else ''
  534. if not key.startswith('CONFIG_'):
  535. continue
  536. elif not line or line[0] in ['#', '*', '/']:
  537. continue
  538. else:
  539. key, value = line.split('=', 1)
  540. if self.squash_config_y and value == 'y':
  541. value = '1'
  542. config[key] = value
  543. return config
  544. def _ProcessEnvironment(self, fname):
  545. """Read in a uboot.env file
  546. This function reads in environment variables from a file.
  547. Args:
  548. fname: Filename to read
  549. Returns:
  550. Dictionary:
  551. key: environment variable (e.g. bootlimit)
  552. value: value of environment variable (e.g. 1)
  553. """
  554. environment = {}
  555. if os.path.exists(fname):
  556. with open(fname) as fd:
  557. for line in fd.read().split('\0'):
  558. try:
  559. key, value = line.split('=', 1)
  560. environment[key] = value
  561. except ValueError:
  562. # ignore lines we can't parse
  563. pass
  564. return environment
  565. def GetBuildOutcome(self, commit_upto, target, read_func_sizes,
  566. read_config, read_environment):
  567. """Work out the outcome of a build.
  568. Args:
  569. commit_upto: Commit number to check (0..n-1)
  570. target: Target board to check
  571. read_func_sizes: True to read function size information
  572. read_config: True to read .config and autoconf.h files
  573. read_environment: True to read uboot.env files
  574. Returns:
  575. Outcome object
  576. """
  577. done_file = self.GetDoneFile(commit_upto, target)
  578. sizes_file = self.GetSizesFile(commit_upto, target)
  579. sizes = {}
  580. func_sizes = {}
  581. config = {}
  582. environment = {}
  583. if os.path.exists(done_file):
  584. with open(done_file, 'r') as fd:
  585. try:
  586. return_code = int(fd.readline())
  587. except ValueError:
  588. # The file may be empty due to running out of disk space.
  589. # Try a rebuild
  590. return_code = 1
  591. err_lines = []
  592. err_file = self.GetErrFile(commit_upto, target)
  593. if os.path.exists(err_file):
  594. with open(err_file, 'r') as fd:
  595. err_lines = self.FilterErrors(fd.readlines())
  596. # Decide whether the build was ok, failed or created warnings
  597. if return_code:
  598. rc = OUTCOME_ERROR
  599. elif len(err_lines):
  600. rc = OUTCOME_WARNING
  601. else:
  602. rc = OUTCOME_OK
  603. # Convert size information to our simple format
  604. if os.path.exists(sizes_file):
  605. with open(sizes_file, 'r') as fd:
  606. for line in fd.readlines():
  607. values = line.split()
  608. rodata = 0
  609. if len(values) > 6:
  610. rodata = int(values[6], 16)
  611. size_dict = {
  612. 'all' : int(values[0]) + int(values[1]) +
  613. int(values[2]),
  614. 'text' : int(values[0]) - rodata,
  615. 'data' : int(values[1]),
  616. 'bss' : int(values[2]),
  617. 'rodata' : rodata,
  618. }
  619. sizes[values[5]] = size_dict
  620. if read_func_sizes:
  621. pattern = self.GetFuncSizesFile(commit_upto, target, '*')
  622. for fname in glob.glob(pattern):
  623. with open(fname, 'r') as fd:
  624. dict_name = os.path.basename(fname).replace('.sizes',
  625. '')
  626. func_sizes[dict_name] = self.ReadFuncSizes(fname, fd)
  627. if read_config:
  628. output_dir = self.GetBuildDir(commit_upto, target)
  629. for name in self.config_filenames:
  630. fname = os.path.join(output_dir, name)
  631. config[name] = self._ProcessConfig(fname)
  632. if read_environment:
  633. output_dir = self.GetBuildDir(commit_upto, target)
  634. fname = os.path.join(output_dir, 'uboot.env')
  635. environment = self._ProcessEnvironment(fname)
  636. return Builder.Outcome(rc, err_lines, sizes, func_sizes, config,
  637. environment)
  638. return Builder.Outcome(OUTCOME_UNKNOWN, [], {}, {}, {}, {})
  639. def GetResultSummary(self, boards_selected, commit_upto, read_func_sizes,
  640. read_config, read_environment):
  641. """Calculate a summary of the results of building a commit.
  642. Args:
  643. board_selected: Dict containing boards to summarise
  644. commit_upto: Commit number to summarize (0..self.count-1)
  645. read_func_sizes: True to read function size information
  646. read_config: True to read .config and autoconf.h files
  647. read_environment: True to read uboot.env files
  648. Returns:
  649. Tuple:
  650. Dict containing boards which passed building this commit.
  651. keyed by board.target
  652. List containing a summary of error lines
  653. Dict keyed by error line, containing a list of the Board
  654. objects with that error
  655. List containing a summary of warning lines
  656. Dict keyed by error line, containing a list of the Board
  657. objects with that warning
  658. Dictionary keyed by board.target. Each value is a dictionary:
  659. key: filename - e.g. '.config'
  660. value is itself a dictionary:
  661. key: config name
  662. value: config value
  663. Dictionary keyed by board.target. Each value is a dictionary:
  664. key: environment variable
  665. value: value of environment variable
  666. """
  667. def AddLine(lines_summary, lines_boards, line, board):
  668. line = line.rstrip()
  669. if line in lines_boards:
  670. lines_boards[line].append(board)
  671. else:
  672. lines_boards[line] = [board]
  673. lines_summary.append(line)
  674. board_dict = {}
  675. err_lines_summary = []
  676. err_lines_boards = {}
  677. warn_lines_summary = []
  678. warn_lines_boards = {}
  679. config = {}
  680. environment = {}
  681. for board in boards_selected.values():
  682. outcome = self.GetBuildOutcome(commit_upto, board.target,
  683. read_func_sizes, read_config,
  684. read_environment)
  685. board_dict[board.target] = outcome
  686. last_func = None
  687. last_was_warning = False
  688. for line in outcome.err_lines:
  689. if line:
  690. if (self._re_function.match(line) or
  691. self._re_files.match(line)):
  692. last_func = line
  693. else:
  694. is_warning = (self._re_warning.match(line) or
  695. self._re_dtb_warning.match(line))
  696. is_note = self._re_note.match(line)
  697. if is_warning or (last_was_warning and is_note):
  698. if last_func:
  699. AddLine(warn_lines_summary, warn_lines_boards,
  700. last_func, board)
  701. AddLine(warn_lines_summary, warn_lines_boards,
  702. line, board)
  703. else:
  704. if last_func:
  705. AddLine(err_lines_summary, err_lines_boards,
  706. last_func, board)
  707. AddLine(err_lines_summary, err_lines_boards,
  708. line, board)
  709. last_was_warning = is_warning
  710. last_func = None
  711. tconfig = Config(self.config_filenames, board.target)
  712. for fname in self.config_filenames:
  713. if outcome.config:
  714. for key, value in outcome.config[fname].items():
  715. tconfig.Add(fname, key, value)
  716. config[board.target] = tconfig
  717. tenvironment = Environment(board.target)
  718. if outcome.environment:
  719. for key, value in outcome.environment.items():
  720. tenvironment.Add(key, value)
  721. environment[board.target] = tenvironment
  722. return (board_dict, err_lines_summary, err_lines_boards,
  723. warn_lines_summary, warn_lines_boards, config, environment)
  724. def AddOutcome(self, board_dict, arch_list, changes, char, color):
  725. """Add an output to our list of outcomes for each architecture
  726. This simple function adds failing boards (changes) to the
  727. relevant architecture string, so we can print the results out
  728. sorted by architecture.
  729. Args:
  730. board_dict: Dict containing all boards
  731. arch_list: Dict keyed by arch name. Value is a string containing
  732. a list of board names which failed for that arch.
  733. changes: List of boards to add to arch_list
  734. color: terminal.Colour object
  735. """
  736. done_arch = {}
  737. for target in changes:
  738. if target in board_dict:
  739. arch = board_dict[target].arch
  740. else:
  741. arch = 'unknown'
  742. str = self.col.Color(color, ' ' + target)
  743. if not arch in done_arch:
  744. str = ' %s %s' % (self.col.Color(color, char), str)
  745. done_arch[arch] = True
  746. if not arch in arch_list:
  747. arch_list[arch] = str
  748. else:
  749. arch_list[arch] += str
  750. def ColourNum(self, num):
  751. color = self.col.RED if num > 0 else self.col.GREEN
  752. if num == 0:
  753. return '0'
  754. return self.col.Color(color, str(num))
  755. def ResetResultSummary(self, board_selected):
  756. """Reset the results summary ready for use.
  757. Set up the base board list to be all those selected, and set the
  758. error lines to empty.
  759. Following this, calls to PrintResultSummary() will use this
  760. information to work out what has changed.
  761. Args:
  762. board_selected: Dict containing boards to summarise, keyed by
  763. board.target
  764. """
  765. self._base_board_dict = {}
  766. for board in board_selected:
  767. self._base_board_dict[board] = Builder.Outcome(0, [], [], {}, {},
  768. {})
  769. self._base_err_lines = []
  770. self._base_warn_lines = []
  771. self._base_err_line_boards = {}
  772. self._base_warn_line_boards = {}
  773. self._base_config = None
  774. self._base_environment = None
  775. def PrintFuncSizeDetail(self, fname, old, new):
  776. grow, shrink, add, remove, up, down = 0, 0, 0, 0, 0, 0
  777. delta, common = [], {}
  778. for a in old:
  779. if a in new:
  780. common[a] = 1
  781. for name in old:
  782. if name not in common:
  783. remove += 1
  784. down += old[name]
  785. delta.append([-old[name], name])
  786. for name in new:
  787. if name not in common:
  788. add += 1
  789. up += new[name]
  790. delta.append([new[name], name])
  791. for name in common:
  792. diff = new.get(name, 0) - old.get(name, 0)
  793. if diff > 0:
  794. grow, up = grow + 1, up + diff
  795. elif diff < 0:
  796. shrink, down = shrink + 1, down - diff
  797. delta.append([diff, name])
  798. delta.sort()
  799. delta.reverse()
  800. args = [add, -remove, grow, -shrink, up, -down, up - down]
  801. if max(args) == 0 and min(args) == 0:
  802. return
  803. args = [self.ColourNum(x) for x in args]
  804. indent = ' ' * 15
  805. Print('%s%s: add: %s/%s, grow: %s/%s bytes: %s/%s (%s)' %
  806. tuple([indent, self.col.Color(self.col.YELLOW, fname)] + args))
  807. Print('%s %-38s %7s %7s %+7s' % (indent, 'function', 'old', 'new',
  808. 'delta'))
  809. for diff, name in delta:
  810. if diff:
  811. color = self.col.RED if diff > 0 else self.col.GREEN
  812. msg = '%s %-38s %7s %7s %+7d' % (indent, name,
  813. old.get(name, '-'), new.get(name,'-'), diff)
  814. Print(msg, colour=color)
  815. def PrintSizeDetail(self, target_list, show_bloat):
  816. """Show details size information for each board
  817. Args:
  818. target_list: List of targets, each a dict containing:
  819. 'target': Target name
  820. 'total_diff': Total difference in bytes across all areas
  821. <part_name>: Difference for that part
  822. show_bloat: Show detail for each function
  823. """
  824. targets_by_diff = sorted(target_list, reverse=True,
  825. key=lambda x: x['_total_diff'])
  826. for result in targets_by_diff:
  827. printed_target = False
  828. for name in sorted(result):
  829. diff = result[name]
  830. if name.startswith('_'):
  831. continue
  832. if diff != 0:
  833. color = self.col.RED if diff > 0 else self.col.GREEN
  834. msg = ' %s %+d' % (name, diff)
  835. if not printed_target:
  836. Print('%10s %-15s:' % ('', result['_target']),
  837. newline=False)
  838. printed_target = True
  839. Print(msg, colour=color, newline=False)
  840. if printed_target:
  841. Print()
  842. if show_bloat:
  843. target = result['_target']
  844. outcome = result['_outcome']
  845. base_outcome = self._base_board_dict[target]
  846. for fname in outcome.func_sizes:
  847. self.PrintFuncSizeDetail(fname,
  848. base_outcome.func_sizes[fname],
  849. outcome.func_sizes[fname])
  850. def PrintSizeSummary(self, board_selected, board_dict, show_detail,
  851. show_bloat):
  852. """Print a summary of image sizes broken down by section.
  853. The summary takes the form of one line per architecture. The
  854. line contains deltas for each of the sections (+ means the section
  855. got bigger, - means smaller). The nunmbers are the average number
  856. of bytes that a board in this section increased by.
  857. For example:
  858. powerpc: (622 boards) text -0.0
  859. arm: (285 boards) text -0.0
  860. nds32: (3 boards) text -8.0
  861. Args:
  862. board_selected: Dict containing boards to summarise, keyed by
  863. board.target
  864. board_dict: Dict containing boards for which we built this
  865. commit, keyed by board.target. The value is an Outcome object.
  866. show_detail: Show detail for each board
  867. show_bloat: Show detail for each function
  868. """
  869. arch_list = {}
  870. arch_count = {}
  871. # Calculate changes in size for different image parts
  872. # The previous sizes are in Board.sizes, for each board
  873. for target in board_dict:
  874. if target not in board_selected:
  875. continue
  876. base_sizes = self._base_board_dict[target].sizes
  877. outcome = board_dict[target]
  878. sizes = outcome.sizes
  879. # Loop through the list of images, creating a dict of size
  880. # changes for each image/part. We end up with something like
  881. # {'target' : 'snapper9g45, 'data' : 5, 'u-boot-spl:text' : -4}
  882. # which means that U-Boot data increased by 5 bytes and SPL
  883. # text decreased by 4.
  884. err = {'_target' : target}
  885. for image in sizes:
  886. if image in base_sizes:
  887. base_image = base_sizes[image]
  888. # Loop through the text, data, bss parts
  889. for part in sorted(sizes[image]):
  890. diff = sizes[image][part] - base_image[part]
  891. col = None
  892. if diff:
  893. if image == 'u-boot':
  894. name = part
  895. else:
  896. name = image + ':' + part
  897. err[name] = diff
  898. arch = board_selected[target].arch
  899. if not arch in arch_count:
  900. arch_count[arch] = 1
  901. else:
  902. arch_count[arch] += 1
  903. if not sizes:
  904. pass # Only add to our list when we have some stats
  905. elif not arch in arch_list:
  906. arch_list[arch] = [err]
  907. else:
  908. arch_list[arch].append(err)
  909. # We now have a list of image size changes sorted by arch
  910. # Print out a summary of these
  911. for arch, target_list in arch_list.items():
  912. # Get total difference for each type
  913. totals = {}
  914. for result in target_list:
  915. total = 0
  916. for name, diff in result.items():
  917. if name.startswith('_'):
  918. continue
  919. total += diff
  920. if name in totals:
  921. totals[name] += diff
  922. else:
  923. totals[name] = diff
  924. result['_total_diff'] = total
  925. result['_outcome'] = board_dict[result['_target']]
  926. count = len(target_list)
  927. printed_arch = False
  928. for name in sorted(totals):
  929. diff = totals[name]
  930. if diff:
  931. # Display the average difference in this name for this
  932. # architecture
  933. avg_diff = float(diff) / count
  934. color = self.col.RED if avg_diff > 0 else self.col.GREEN
  935. msg = ' %s %+1.1f' % (name, avg_diff)
  936. if not printed_arch:
  937. Print('%10s: (for %d/%d boards)' % (arch, count,
  938. arch_count[arch]), newline=False)
  939. printed_arch = True
  940. Print(msg, colour=color, newline=False)
  941. if printed_arch:
  942. Print()
  943. if show_detail:
  944. self.PrintSizeDetail(target_list, show_bloat)
  945. def PrintResultSummary(self, board_selected, board_dict, err_lines,
  946. err_line_boards, warn_lines, warn_line_boards,
  947. config, environment, show_sizes, show_detail,
  948. show_bloat, show_config, show_environment):
  949. """Compare results with the base results and display delta.
  950. Only boards mentioned in board_selected will be considered. This
  951. function is intended to be called repeatedly with the results of
  952. each commit. It therefore shows a 'diff' between what it saw in
  953. the last call and what it sees now.
  954. Args:
  955. board_selected: Dict containing boards to summarise, keyed by
  956. board.target
  957. board_dict: Dict containing boards for which we built this
  958. commit, keyed by board.target. The value is an Outcome object.
  959. err_lines: A list of errors for this commit, or [] if there is
  960. none, or we don't want to print errors
  961. err_line_boards: Dict keyed by error line, containing a list of
  962. the Board objects with that error
  963. warn_lines: A list of warnings for this commit, or [] if there is
  964. none, or we don't want to print errors
  965. warn_line_boards: Dict keyed by warning line, containing a list of
  966. the Board objects with that warning
  967. config: Dictionary keyed by filename - e.g. '.config'. Each
  968. value is itself a dictionary:
  969. key: config name
  970. value: config value
  971. environment: Dictionary keyed by environment variable, Each
  972. value is the value of environment variable.
  973. show_sizes: Show image size deltas
  974. show_detail: Show detail for each board
  975. show_bloat: Show detail for each function
  976. show_config: Show config changes
  977. show_environment: Show environment changes
  978. """
  979. def _BoardList(line, line_boards):
  980. """Helper function to get a line of boards containing a line
  981. Args:
  982. line: Error line to search for
  983. Return:
  984. String containing a list of boards with that error line, or
  985. '' if the user has not requested such a list
  986. """
  987. if self._list_error_boards:
  988. names = []
  989. for board in line_boards[line]:
  990. if not board.target in names:
  991. names.append(board.target)
  992. names_str = '(%s) ' % ','.join(names)
  993. else:
  994. names_str = ''
  995. return names_str
  996. def _CalcErrorDelta(base_lines, base_line_boards, lines, line_boards,
  997. char):
  998. better_lines = []
  999. worse_lines = []
  1000. for line in lines:
  1001. if line not in base_lines:
  1002. worse_lines.append(char + '+' +
  1003. _BoardList(line, line_boards) + line)
  1004. for line in base_lines:
  1005. if line not in lines:
  1006. better_lines.append(char + '-' +
  1007. _BoardList(line, base_line_boards) + line)
  1008. return better_lines, worse_lines
  1009. def _CalcConfig(delta, name, config):
  1010. """Calculate configuration changes
  1011. Args:
  1012. delta: Type of the delta, e.g. '+'
  1013. name: name of the file which changed (e.g. .config)
  1014. config: configuration change dictionary
  1015. key: config name
  1016. value: config value
  1017. Returns:
  1018. String containing the configuration changes which can be
  1019. printed
  1020. """
  1021. out = ''
  1022. for key in sorted(config.keys()):
  1023. out += '%s=%s ' % (key, config[key])
  1024. return '%s %s: %s' % (delta, name, out)
  1025. def _AddConfig(lines, name, config_plus, config_minus, config_change):
  1026. """Add changes in configuration to a list
  1027. Args:
  1028. lines: list to add to
  1029. name: config file name
  1030. config_plus: configurations added, dictionary
  1031. key: config name
  1032. value: config value
  1033. config_minus: configurations removed, dictionary
  1034. key: config name
  1035. value: config value
  1036. config_change: configurations changed, dictionary
  1037. key: config name
  1038. value: config value
  1039. """
  1040. if config_plus:
  1041. lines.append(_CalcConfig('+', name, config_plus))
  1042. if config_minus:
  1043. lines.append(_CalcConfig('-', name, config_minus))
  1044. if config_change:
  1045. lines.append(_CalcConfig('c', name, config_change))
  1046. def _OutputConfigInfo(lines):
  1047. for line in lines:
  1048. if not line:
  1049. continue
  1050. if line[0] == '+':
  1051. col = self.col.GREEN
  1052. elif line[0] == '-':
  1053. col = self.col.RED
  1054. elif line[0] == 'c':
  1055. col = self.col.YELLOW
  1056. Print(' ' + line, newline=True, colour=col)
  1057. ok_boards = [] # List of boards fixed since last commit
  1058. warn_boards = [] # List of boards with warnings since last commit
  1059. err_boards = [] # List of new broken boards since last commit
  1060. new_boards = [] # List of boards that didn't exist last time
  1061. unknown_boards = [] # List of boards that were not built
  1062. for target in board_dict:
  1063. if target not in board_selected:
  1064. continue
  1065. # If the board was built last time, add its outcome to a list
  1066. if target in self._base_board_dict:
  1067. base_outcome = self._base_board_dict[target].rc
  1068. outcome = board_dict[target]
  1069. if outcome.rc == OUTCOME_UNKNOWN:
  1070. unknown_boards.append(target)
  1071. elif outcome.rc < base_outcome:
  1072. if outcome.rc == OUTCOME_WARNING:
  1073. warn_boards.append(target)
  1074. else:
  1075. ok_boards.append(target)
  1076. elif outcome.rc > base_outcome:
  1077. if outcome.rc == OUTCOME_WARNING:
  1078. warn_boards.append(target)
  1079. else:
  1080. err_boards.append(target)
  1081. else:
  1082. new_boards.append(target)
  1083. # Get a list of errors that have appeared, and disappeared
  1084. better_err, worse_err = _CalcErrorDelta(self._base_err_lines,
  1085. self._base_err_line_boards, err_lines, err_line_boards, '')
  1086. better_warn, worse_warn = _CalcErrorDelta(self._base_warn_lines,
  1087. self._base_warn_line_boards, warn_lines, warn_line_boards, 'w')
  1088. # Display results by arch
  1089. if any((ok_boards, warn_boards, err_boards, unknown_boards, new_boards,
  1090. worse_err, better_err, worse_warn, better_warn)):
  1091. arch_list = {}
  1092. self.AddOutcome(board_selected, arch_list, ok_boards, '',
  1093. self.col.GREEN)
  1094. self.AddOutcome(board_selected, arch_list, warn_boards, 'w+',
  1095. self.col.YELLOW)
  1096. self.AddOutcome(board_selected, arch_list, err_boards, '+',
  1097. self.col.RED)
  1098. self.AddOutcome(board_selected, arch_list, new_boards, '*', self.col.BLUE)
  1099. if self._show_unknown:
  1100. self.AddOutcome(board_selected, arch_list, unknown_boards, '?',
  1101. self.col.MAGENTA)
  1102. for arch, target_list in arch_list.items():
  1103. Print('%10s: %s' % (arch, target_list))
  1104. self._error_lines += 1
  1105. if better_err:
  1106. Print('\n'.join(better_err), colour=self.col.GREEN)
  1107. self._error_lines += 1
  1108. if worse_err:
  1109. Print('\n'.join(worse_err), colour=self.col.RED)
  1110. self._error_lines += 1
  1111. if better_warn:
  1112. Print('\n'.join(better_warn), colour=self.col.CYAN)
  1113. self._error_lines += 1
  1114. if worse_warn:
  1115. Print('\n'.join(worse_warn), colour=self.col.MAGENTA)
  1116. self._error_lines += 1
  1117. if show_sizes:
  1118. self.PrintSizeSummary(board_selected, board_dict, show_detail,
  1119. show_bloat)
  1120. if show_environment and self._base_environment:
  1121. lines = []
  1122. for target in board_dict:
  1123. if target not in board_selected:
  1124. continue
  1125. tbase = self._base_environment[target]
  1126. tenvironment = environment[target]
  1127. environment_plus = {}
  1128. environment_minus = {}
  1129. environment_change = {}
  1130. base = tbase.environment
  1131. for key, value in tenvironment.environment.items():
  1132. if key not in base:
  1133. environment_plus[key] = value
  1134. for key, value in base.items():
  1135. if key not in tenvironment.environment:
  1136. environment_minus[key] = value
  1137. for key, value in base.items():
  1138. new_value = tenvironment.environment.get(key)
  1139. if new_value and value != new_value:
  1140. desc = '%s -> %s' % (value, new_value)
  1141. environment_change[key] = desc
  1142. _AddConfig(lines, target, environment_plus, environment_minus,
  1143. environment_change)
  1144. _OutputConfigInfo(lines)
  1145. if show_config and self._base_config:
  1146. summary = {}
  1147. arch_config_plus = {}
  1148. arch_config_minus = {}
  1149. arch_config_change = {}
  1150. arch_list = []
  1151. for target in board_dict:
  1152. if target not in board_selected:
  1153. continue
  1154. arch = board_selected[target].arch
  1155. if arch not in arch_list:
  1156. arch_list.append(arch)
  1157. for arch in arch_list:
  1158. arch_config_plus[arch] = {}
  1159. arch_config_minus[arch] = {}
  1160. arch_config_change[arch] = {}
  1161. for name in self.config_filenames:
  1162. arch_config_plus[arch][name] = {}
  1163. arch_config_minus[arch][name] = {}
  1164. arch_config_change[arch][name] = {}
  1165. for target in board_dict:
  1166. if target not in board_selected:
  1167. continue
  1168. arch = board_selected[target].arch
  1169. all_config_plus = {}
  1170. all_config_minus = {}
  1171. all_config_change = {}
  1172. tbase = self._base_config[target]
  1173. tconfig = config[target]
  1174. lines = []
  1175. for name in self.config_filenames:
  1176. if not tconfig.config[name]:
  1177. continue
  1178. config_plus = {}
  1179. config_minus = {}
  1180. config_change = {}
  1181. base = tbase.config[name]
  1182. for key, value in tconfig.config[name].items():
  1183. if key not in base:
  1184. config_plus[key] = value
  1185. all_config_plus[key] = value
  1186. for key, value in base.items():
  1187. if key not in tconfig.config[name]:
  1188. config_minus[key] = value
  1189. all_config_minus[key] = value
  1190. for key, value in base.items():
  1191. new_value = tconfig.config.get(key)
  1192. if new_value and value != new_value:
  1193. desc = '%s -> %s' % (value, new_value)
  1194. config_change[key] = desc
  1195. all_config_change[key] = desc
  1196. arch_config_plus[arch][name].update(config_plus)
  1197. arch_config_minus[arch][name].update(config_minus)
  1198. arch_config_change[arch][name].update(config_change)
  1199. _AddConfig(lines, name, config_plus, config_minus,
  1200. config_change)
  1201. _AddConfig(lines, 'all', all_config_plus, all_config_minus,
  1202. all_config_change)
  1203. summary[target] = '\n'.join(lines)
  1204. lines_by_target = {}
  1205. for target, lines in summary.items():
  1206. if lines in lines_by_target:
  1207. lines_by_target[lines].append(target)
  1208. else:
  1209. lines_by_target[lines] = [target]
  1210. for arch in arch_list:
  1211. lines = []
  1212. all_plus = {}
  1213. all_minus = {}
  1214. all_change = {}
  1215. for name in self.config_filenames:
  1216. all_plus.update(arch_config_plus[arch][name])
  1217. all_minus.update(arch_config_minus[arch][name])
  1218. all_change.update(arch_config_change[arch][name])
  1219. _AddConfig(lines, name, arch_config_plus[arch][name],
  1220. arch_config_minus[arch][name],
  1221. arch_config_change[arch][name])
  1222. _AddConfig(lines, 'all', all_plus, all_minus, all_change)
  1223. #arch_summary[target] = '\n'.join(lines)
  1224. if lines:
  1225. Print('%s:' % arch)
  1226. _OutputConfigInfo(lines)
  1227. for lines, targets in lines_by_target.items():
  1228. if not lines:
  1229. continue
  1230. Print('%s :' % ' '.join(sorted(targets)))
  1231. _OutputConfigInfo(lines.split('\n'))
  1232. # Save our updated information for the next call to this function
  1233. self._base_board_dict = board_dict
  1234. self._base_err_lines = err_lines
  1235. self._base_warn_lines = warn_lines
  1236. self._base_err_line_boards = err_line_boards
  1237. self._base_warn_line_boards = warn_line_boards
  1238. self._base_config = config
  1239. self._base_environment = environment
  1240. # Get a list of boards that did not get built, if needed
  1241. not_built = []
  1242. for board in board_selected:
  1243. if not board in board_dict:
  1244. not_built.append(board)
  1245. if not_built:
  1246. Print("Boards not built (%d): %s" % (len(not_built),
  1247. ', '.join(not_built)))
  1248. def ProduceResultSummary(self, commit_upto, commits, board_selected):
  1249. (board_dict, err_lines, err_line_boards, warn_lines,
  1250. warn_line_boards, config, environment) = self.GetResultSummary(
  1251. board_selected, commit_upto,
  1252. read_func_sizes=self._show_bloat,
  1253. read_config=self._show_config,
  1254. read_environment=self._show_environment)
  1255. if commits:
  1256. msg = '%02d: %s' % (commit_upto + 1,
  1257. commits[commit_upto].subject)
  1258. Print(msg, colour=self.col.BLUE)
  1259. self.PrintResultSummary(board_selected, board_dict,
  1260. err_lines if self._show_errors else [], err_line_boards,
  1261. warn_lines if self._show_errors else [], warn_line_boards,
  1262. config, environment, self._show_sizes, self._show_detail,
  1263. self._show_bloat, self._show_config, self._show_environment)
  1264. def ShowSummary(self, commits, board_selected):
  1265. """Show a build summary for U-Boot for a given board list.
  1266. Reset the result summary, then repeatedly call GetResultSummary on
  1267. each commit's results, then display the differences we see.
  1268. Args:
  1269. commit: Commit objects to summarise
  1270. board_selected: Dict containing boards to summarise
  1271. """
  1272. self.commit_count = len(commits) if commits else 1
  1273. self.commits = commits
  1274. self.ResetResultSummary(board_selected)
  1275. self._error_lines = 0
  1276. for commit_upto in range(0, self.commit_count, self._step):
  1277. self.ProduceResultSummary(commit_upto, commits, board_selected)
  1278. if not self._error_lines:
  1279. Print('(no errors to report)', colour=self.col.GREEN)
  1280. def SetupBuild(self, board_selected, commits):
  1281. """Set up ready to start a build.
  1282. Args:
  1283. board_selected: Selected boards to build
  1284. commits: Selected commits to build
  1285. """
  1286. # First work out how many commits we will build
  1287. count = (self.commit_count + self._step - 1) // self._step
  1288. self.count = len(board_selected) * count
  1289. self.upto = self.warned = self.fail = 0
  1290. self._timestamps = collections.deque()
  1291. def GetThreadDir(self, thread_num):
  1292. """Get the directory path to the working dir for a thread.
  1293. Args:
  1294. thread_num: Number of thread to check.
  1295. """
  1296. return os.path.join(self._working_dir, '%02d' % thread_num)
  1297. def _PrepareThread(self, thread_num, setup_git):
  1298. """Prepare the working directory for a thread.
  1299. This clones or fetches the repo into the thread's work directory.
  1300. Args:
  1301. thread_num: Thread number (0, 1, ...)
  1302. setup_git: True to set up a git repo clone
  1303. """
  1304. thread_dir = self.GetThreadDir(thread_num)
  1305. builderthread.Mkdir(thread_dir)
  1306. git_dir = os.path.join(thread_dir, '.git')
  1307. # Clone the repo if it doesn't already exist
  1308. # TODO(sjg@chromium): Perhaps some git hackery to symlink instead, so
  1309. # we have a private index but uses the origin repo's contents?
  1310. if setup_git and self.git_dir:
  1311. src_dir = os.path.abspath(self.git_dir)
  1312. if os.path.exists(git_dir):
  1313. gitutil.Fetch(git_dir, thread_dir)
  1314. else:
  1315. Print('\rCloning repo for thread %d' % thread_num,
  1316. newline=False)
  1317. gitutil.Clone(src_dir, thread_dir)
  1318. Print('\r%s\r' % (' ' * 30), newline=False)
  1319. def _PrepareWorkingSpace(self, max_threads, setup_git):
  1320. """Prepare the working directory for use.
  1321. Set up the git repo for each thread.
  1322. Args:
  1323. max_threads: Maximum number of threads we expect to need.
  1324. setup_git: True to set up a git repo clone
  1325. """
  1326. builderthread.Mkdir(self._working_dir)
  1327. for thread in range(max_threads):
  1328. self._PrepareThread(thread, setup_git)
  1329. def _PrepareOutputSpace(self):
  1330. """Get the output directories ready to receive files.
  1331. We delete any output directories which look like ones we need to
  1332. create. Having left over directories is confusing when the user wants
  1333. to check the output manually.
  1334. """
  1335. if not self.commits:
  1336. return
  1337. dir_list = []
  1338. for commit_upto in range(self.commit_count):
  1339. dir_list.append(self._GetOutputDir(commit_upto))
  1340. to_remove = []
  1341. for dirname in glob.glob(os.path.join(self.base_dir, '*')):
  1342. if dirname not in dir_list:
  1343. to_remove.append(dirname)
  1344. if to_remove:
  1345. Print('Removing %d old build directories' % len(to_remove),
  1346. newline=False)
  1347. for dirname in to_remove:
  1348. shutil.rmtree(dirname)
  1349. def BuildBoards(self, commits, board_selected, keep_outputs, verbose):
  1350. """Build all commits for a list of boards
  1351. Args:
  1352. commits: List of commits to be build, each a Commit object
  1353. boards_selected: Dict of selected boards, key is target name,
  1354. value is Board object
  1355. keep_outputs: True to save build output files
  1356. verbose: Display build results as they are completed
  1357. Returns:
  1358. Tuple containing:
  1359. - number of boards that failed to build
  1360. - number of boards that issued warnings
  1361. """
  1362. self.commit_count = len(commits) if commits else 1
  1363. self.commits = commits
  1364. self._verbose = verbose
  1365. self.ResetResultSummary(board_selected)
  1366. builderthread.Mkdir(self.base_dir, parents = True)
  1367. self._PrepareWorkingSpace(min(self.num_threads, len(board_selected)),
  1368. commits is not None)
  1369. self._PrepareOutputSpace()
  1370. Print('\rStarting build...', newline=False)
  1371. self.SetupBuild(board_selected, commits)
  1372. self.ProcessResult(None)
  1373. # Create jobs to build all commits for each board
  1374. for brd in board_selected.values():
  1375. job = builderthread.BuilderJob()
  1376. job.board = brd
  1377. job.commits = commits
  1378. job.keep_outputs = keep_outputs
  1379. job.step = self._step
  1380. self.queue.put(job)
  1381. term = threading.Thread(target=self.queue.join)
  1382. term.setDaemon(True)
  1383. term.start()
  1384. while term.isAlive():
  1385. term.join(100)
  1386. # Wait until we have processed all output
  1387. self.out_queue.join()
  1388. Print()
  1389. self.ClearLine(0)
  1390. return (self.fail, self.warned)